Writing data into CSV file C#

Submitted by admin on Tue, 05/09/2017 - 19:43

Writing data into CSV file

If  you already have a loop, contemplate doing it like this:

[geshifilter-code]//before your loop [/geshifilter-code]

[geshifilter-code]var csv = new StringBuilder(); [/geshifilter-code]

[geshifilter-code]//in your loop [/geshifilter-code]

[geshifilter-code]var first = reader[0].ToString(); [/geshifilter-code]

[geshifilter-code]var second = image.ToString(); [/geshifilter-code]

[geshifilter-code]//Suggestion for erick[/geshifilter-code]

[geshifilter-code]var newLine = string.Format("{0},{1}", first, second); [/geshifilter-code]

[geshifilter-code]csv.AppendLine(newLine); [/geshifilter-code]

[geshifilter-code]//after your loop [/geshifilter-code]

[geshifilter-code]File.WriteAllText(filePath, csv.ToString()); [/geshifilter-code]

Alternatively, something to this effect. My reasoning is: you will not need writing to the file for every item, you will simply be opening the stream once and then writing to it.

You can replace

[geshifilter-code]File.WriteAllText(filePath, csv.ToString());[/geshifilter-code]


[geshifilter-code]File.AppendAllText(filePath, csv.ToString());[/geshifilter-code]

if you want to keep previous versions of csv in the same file

C# 6

If you are using c# 6.0, then you can do the following

[geshifilter-code]var newLine = $"{first},{second}"[/geshifilter-code]


 what [geshifilter-code]Environment.NewLine[/geshifilter-code] does