Remove space outside quotes marks comma in txt file - c#

I have a txt file that I need to insert data from that file.
I am getting the file from a folder and put in another folder before isnerting into SQL. I need to remove all spaces before storing in the folder. I am using this c# code:
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
//transferResult = session.PutFiles(FileSource + FileName, FileDestination, false, transferOptions);
transferResult = session.GetFiles(FileSource + FileNameSource, FileDestination + FileNameDestination, false, transferOptions);
// Throw on any error
transferResult.Check();
The format of files is separated by comma but with quotes marks like this:
However this file has a lof of spaces after last column. I need to remove that spaces.
Does anyone know how can I remove that space:

If i got your problem here you are :
fileContents = fileContents.Replace(" ", "");
Then you can put the modified text back to the file. Otherwise:
fileContents = fileContents.replaceAll("\\s+", "");

Related

Make a new file who's name is a directory path

I'm creating a csv file with a bunch of data. This file is going to be pushed up to another location and its name is going to be used to put it in the directory it belongs in. I need to create the filename to mimic a directory, without actually using that directory.
I'm using the below, basically "outputDirectory" is where the file should live, everything after it needs to be part of the filename.
String fileName = outputDirectory + DateTime.Now.ToString("yyyy-mm-hh") + "//" + app + "//" + client +"//" + site +"//" + unit + ".csv";
using (StreamWriter sw = new StreamWriter(fileName, false))
{
foreach (AFValue AFval in AFvals)
{
string tagname = AFval.PIPoint.Name;
string timestamp = AFval.Timestamp.ToString();
string value = AFval.Value.ToString();
var newLine = string.Format("{0},{1},{2}", tagname, timestamp, value);
sw.Write(newLine);
sw.Write(Environment.NewLine);
}
}
So right now this code is throwing an exception with
'Could not find a part of the path 'C:\Users\user\Desktop\Output\2019-53-01\app\client\site\Unit.csv'.'
I need it to create a file in 'C:\Users\user\Desktop\Output\' called
2019-53-01\app\client\site\Unit.csv'.'
Any ideas?
You cannot use the slash **** in the file name.
Here is an excerpt from Naming Files, Paths, and Namespaces
Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:
The following reserved characters:
< (less than)
(greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
(asterisk)
Integer value zero, sometimes referred to as the ASCII NUL character.
Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.
Any other character that the target file system does not allow.

Return file located in a specific path

I wrote a method in order to return a file using the return type HttpResposeMessage. I use the below code in order to attach the file.
file.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = newFileName
};
file.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return file;
How can I specify a specific path in to the filename.
I did something like this
fileName = "C://Templates/Order.pdf"
But this renames the file name as C:_Templates_Order.pdf
What I need is to go through the path and grab the file.
You can declare a string literal by using the # symbol in front of the quotes for your string:
fileName = #"C:\templates\order.pdf"
Or you can double escape the backslash
fileName = "C:\\templates\\order.pdf"
You need to put the file name using this simbol \ instead of /
fileName = "C:\\Templates\\Order.pdf";

Find and Delete Characters in String

My program reads registry key values and combines those values with the installation path. I also read the installation path from the registry.
i.e. String dllInstpath = installPath + rKey which equals to:
C:\Program Files (x86)\NSi\AutoStore Workflow 6\HpOXPdCaptureRes.dll
I then use FileVersionInfo on the string above to get the file information of HpOXPdCaptureRes.dll from it's install path and write all the values to a notepad.
My problem is the TRUE dll name does not have 'Res' in the file name. The registry only has the file name with 'Res' in the file name. What I need to do is read from a text file and find all 'Res' and remove them from the line of text within the notepad file.
So the output should look like this:
Current:
HpOXPdCaptureRes.dll
New:
HpOXPdCapture.dll
I have read online and I see the best way to do this is to use ReadAllLines and WriteAllLines. However I am not sure how to implement the find and replace. I have seen a lot of examples on how to remove spaces, invalid characters, etc., but I haven't been able to find an example for what I need.
Summary:
Read text file
Fine Res in all lines of text and remove
Retain current text file, i.e. remove Res and close file
Any help is greatly appreciated.
Thank you!
You can use File.ReadAllLines and File.WriteAllLines.
Example:
Read all the lines and replace the value you want on each line, then write the lines again
File.WriteAllLines("textFilePath",File.ReadAllLines("textFilePath").Select(line => line.Replace("Res.dll", ".dll")));
Just open the file and read all lines using 'File.ReadAllLines'. Then use Replace to remove the Res:
string[] lines = File.ReadAllLines("yourFileName");
var output = lines.Select(x => x.Replace("Res.dll", ".dll")).ToArray();
To later save them back you can use File.WriteAllLines:
File.WriteAllLines("yourFileName", output);
Read everything from file, replace all occurrences of 'res' and write to file:
String filename = "fileName";
StreamReader sr = new StreamReader(filename);
String content = sr.ReadToEnd();
sr.Close();
StreamWriter sw = new StreamWriter(filename);
sw.Write(content.Replace("res", ""));
sw.Close();
If the string you are replacing is guaranteed to be unique in the string - "res.dll" at the end of the string for instance - then you can use Replace method of the String class to do the replacement:
List<string> lines = File.ReadAllLines(sourceFile);
lines = lines.select(l => l.Replace("res.dll", ".dll").ToList();
Or if case sensitivity is an issue:
lines = lines.Select(l => l.Substring(l.Length - 7).ToLower() == "res.dll" ? l.Substring(0, l.Length - 7) + ".dll" : l).ToList();
For more complex cases you might need to use a regular expression to identify the section of the string to replace. Or you might want to split the string int path and filename, modify the filename and join it back together.

How to read a csv file one line at a time and replace/edit certain lines as you go?

I have a 60GB csv file I need to make some modifications to. The customer wants some changes to the files data, but I don't want to regenerate the data in that file because it took 4 days to do.
How can I read the file, line by line (not loading it all into memory!), and make edits to those lines as I go, replacing certain values etc.?
The process would be something like this:
Open a StreamWriter to a temporary file.
Open a StreamReader to the target file.
For each line:
Split the text into columns based on a delimiter.
Check the columns for the values you want to replace, and replace them.
Join the column values back together using your delimiter.
Write the line to the temporary file.
When you are finished, delete the target file, and move the temporary file to the target file path.
Note regarding Steps 2 and 3.1: If you are confident in the structure of your file and it is simple enough, you can do all this out of the box as described (I'll include a sample in a moment). However, there are factors in a CSV file that may need attention (such as recognizing when a delimiter is being used literally in a column value). You can drudge through this yourself, or try an existing solution.
Basic example just using StreamReader and StreamWriter:
var sourcePath = #"C:\data.csv";
var delimiter = ",";
var firstLineContainsHeaders = true;
var tempPath = Path.GetTempFileName();
var lineNumber = 0;
var splitExpression = new Regex(#"(" + delimiter + #")(?=(?:[^""]|""[^""]*"")*$)");
using (var writer = new StreamWriter(tempPath))
using (var reader = new StreamReader(sourcePath))
{
string line = null;
string[] headers = null;
if (firstLineContainsHeaders)
{
line = reader.ReadLine();
lineNumber++;
if (string.IsNullOrEmpty(line)) return; // file is empty;
headers = splitExpression.Split(line).Where(s => s != delimiter).ToArray();
writer.WriteLine(line); // write the original header to the temp file.
}
while ((line = reader.ReadLine()) != null)
{
lineNumber++;
var columns = splitExpression.Split(line).Where(s => s != delimiter).ToArray();
// if there are no headers, do a simple sanity check to make sure you always have the same number of columns in a line
if (headers == null) headers = new string[columns.Length];
if (columns.Length != headers.Length) throw new InvalidOperationException(string.Format("Line {0} is missing one or more columns.", lineNumber));
// TODO: search and replace in columns
// example: replace 'v' in the first column with '\/': if (columns[0].Contains("v")) columns[0] = columns[0].Replace("v", #"\/");
writer.WriteLine(string.Join(delimiter, columns));
}
}
File.Delete(sourcePath);
File.Move(tempPath, sourcePath);
memory-mapped files is a new feature in .NET Framework 4 which can be used to edit large files.
read here http://msdn.microsoft.com/en-us/library/dd997372.aspx
or google Memory-mapped files
Just read the file, line by line, with streamreader, and then use REGEX! The most amazing tool in the world.
using (var sr = new StreamReader(new FileStream(#"C:\temp\file.csv", FileMode.Open)))
{
var line = sr.ReadLine();
while (!sr.EndOfStream)
{
// do stuff
line = sr.ReadLine();
}
}

How to check text file it contains delimiter at the end or not?if it is there how to remove it?

actually i have text file with columns and rows colsep is "'" and row sep is "/"
and my text file is sfsf'fsfsdf'sdfsdf/dfsdf'sfsf'sfsfs/
if my text file contains "/" at the end of the file how to check and remove it it is there
You can use string.TrimEnd()
string str = File.ReadAllText(path);
str = str.TrimEnd('/');
You can use following code:
string fileString = = File.ReadAllText(your file path);
if(fileString[fileString.Length-1].Equals('/'))
{
//your code here;
}
OR you can use:
if(fileString.EndsWith('/'))
{
//yourcode
}
We can check individual characters in string using their index as we all know that:
string is the sequence of characters
this will solve your problem to check last character in file.

Categories