I am trying to write into a csv
file row by row using C# language. Here is my function
string first = reader[0].ToString();
string second=image.ToString();
string csv = string.Format("{0},{1}\n", first, second);
File.WriteAllText(filePath, csv);
The whole function runs inside a loop, and every row should be written to the csv
file. In my case next row overwrites the existing row and in the end I am getting only single record in the csv file which is last one. How can I write all the rows in the csv
file.
Writing csv files by hand can be difficult because your data might contain commas and newlines. I suggest you use an existing library instead.
This question mentions a few options.
Are there any CSV readers/writer libraries in C#?
I would highly recommend you to go the more tedious route. Especially if your file size is large.
File.AppendAllText()
opens a new file, writes the content and then closes the file. Opening files is a much resource-heavy operation, than writing data into open stream. Opening\closing a file inside a loop will cause performance drop.The approach suggested by Johan solves that problem by storing all the output in memory and then writing it once. However (in case of big files) you program will consume a large amount of RAM and even crash with
OutOfMemoryException
Another advantage of my solution is that you can implement pausing\resuming by saving current position in input data.
upd. Placed using in the right place
Simply use AppendAllText instead:
The only downside of the AppendAllText is that it will throw error when file does not exist, so this must be checkedSorry, blonde moment before reading the documentation. Anyway, the WriteAllText method overwrites anything that was previously written in the file, if the file exists.
Note that your current code is not using proper new lines, for example in Notepad you'll see it all as one long line. Change the code to this to have proper new lines:
Instead of reinventing the wheel a library could be used.
CsvHelper
is great for creating and reading csv files. It's read and write operations are stream based and therefore also support operations with a big amount of data.You can write your csv like the following.
As the library is using reflection it will take any type and parse it directly.
If you want to read more about the librarys configurations and possibilities you can do so here.
One simple way to get rid of the overwriting issue is to use
File.AppendText
to append line at the end of the file asHandling Commas
For handling commas inside of values when using
string.Format(...)
, the following has worked for me:So to combine it with Johan's answer, it'd look like this:
Returning CSV File
If you simply wanted to return the file instead of writing it to a location, this is an example of how I accomplished it:
From a Stored Procedure
From a List
Hopefully this is helpful.