I have a CSV file with a lot of trailing spaces in some columns, so I'm trying to write a simple Windows Forms Application that loops through all lines in my CSV and removes the trailing spaces. I think I'm pretty far, but I have the feeling that C# sees this as one line:
"Lorem ipsum dolor sit amet","Default ",9999,1,"base "
While it's supposed to see this as one line:
"Lorem ipsum dolor sit amet"
This is the code I have right now:
String path = @"C:\Users\me\Documents\test.csv";
string[] allLines = File.ReadAllLines(path);
using (StreamWriter sw = new StreamWriter(path))
{
foreach (string line in allLines)
{
if (!string.IsNullOrEmpty(line) && line.Length > 1)
{
line.TrimEnd(' ');
sw.WriteLine(line);
//sw.WriteLine(line.TrimEnd(' '));
}
}
}
Console.WriteLine(allLines);
Console.WriteLine("Done");
How do I make sure that in the case my CSV file is like this:
"Lorem ipsum dolor sit amet ","Default ",9999,1,"base "
"simple","Default ",9999,1," base"
"test ","Default ",9999,1,"base"
It comes out after running the C# code like this (so without the spaces at the end and the beginning):
"Lorem ipsum dolor sit amet","Default ",9999,1,"base"
"simple","Default",9999,1,"base"
"test","Default",9999,1,"base"
Edit: I also tried doing line = line.TrimEnd(' ');
but this gives me the error Cannot assign 'line' because it is a 'foreach iteration variable'.