I been looking at writing to csv file


Oct 24, 2016
Michigan USA
Programming Experience
Hello all,
I spend most of the day looking how to write (something) to a csv file. All of the examples I found was 80,100,120 line long. It is hard for me to be-leave that you need that much code to write something to a file. Does anyone here have any insight into csv files?
thank you
old man:joyous:
A CSV is just a text file. Create a StreamWriter and write each record with a call to WriteLine. Exactly what you pass to that method depends on exactly what you're writing. Here's an example that would write a DataTable with columns containing a text, a number and a date:
using (var writer = new StreamWriter(filePath))
    foreach (DataRow dataRow in myDataTable.Rows)
        writer.WriteLine("\"{0}\",\"{1}\",{2:yyyy-MM-dd HH:mm:ss}",
Note that, in that code, I've wrapped the values for the first two columns in double quotes. That's because they could, under some circumstances, contain commas in the data. If you know for a fact that there will be no commas in the data then you could omit those double quotes if you wanted. You also quote every value, regardless of data type, if you wanted to. The accepted CSV format has no issue with superfluous commas but it does have an issue with commas in unquoted data, so you may prefer to be safer than sorry.
I put that in vs express and it light up like New York City, red lines under everything.

If all you did was copy and paste then that would be no surprise. You need to actually use your brain too. I said that my example will write out the contents of a DataTable and in my example I use a 'myDataTable' variable to represent that. Do you have a myDataTable variable that refers to a DataTable in your code? If not then why would you expect it to magically work? Do you understand what the word "example" actually means? The code I provide demonstrates a principle. In order to do something useful to you, you are supposed to use the example provided to understand the principle demonstrated and then write to implement it for yourself. Why would I bother including code in my example to create and populate a DataTable when anyone who actually wants to write out a DataTable should already have one? Stop and think first.
Top Bottom