I have an input file with fixed columns lengths and I need the file converted to csv using c# code. The current code transforms to csv but the entire row data is not seperated by columns in csv instead stores complete row data values in single cell in each row in converted csv file.
Input text file:-
#Configuration: Tests
#Station All 1st 2nd
# Sat1 Sat2 Sat3 Sat1 Sat2 Sat3 Sat1 Sat2 Sat3
AA 92.88 95.14 93.16 98.31 98.98 100.00 91.31 94.17 93.16
BB 94.57 95.42 93.12 98.21 98.98 99.46 92.88 94.45 92.62
CC 93.26 95.00 92.99 98.49 99.26 100.00 91.85 94.30 92.99
The values should be stored in the similar way in csv file by text values seperated bycolumns.
string sourcefile;
string destfile;
sourcefile=@"C:\\Temp\\NALabc.txt";
destfile=@"C:\\Tempp\\NAL.csv";
int i, j;
StreamWriter csvfile;
string[] lines, cells;
lines = File.ReadAllLines(sourcefile);
csvfile = new StreamWriter(destfile);
for (i = 0; i < lines.Length; i++)
{
cells = lines[i].Split(new Char[] { '\t', ';' });
for (j = 0; j < cells.Length; j++)
csvfile.Write(cells[j] + "\t");
csvfile.WriteLine();
}
csvfile.Close();
I think
csvfile.Write(cells[j] + "\t");
Should instead be
csvfile.Write(cells[j] + ",");
Even with this fix you'll end up with an extra comma at the end of your line. string.Join()
may work better for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.