Writing Data into CSV File in C#

Writing data into CSV file in C#

UPDATE

Back in my naïve days, I suggested doing this manually (it was a simple solution to a simple question), however due to this becoming more and more popular, I'd recommend using the library CsvHelper that does all the safety checks, etc.

CSV is way more complicated than what the question/answer suggests.

Original Answer

As you already have a loop, consider doing it like this:

//before your loop
var csv = new StringBuilder();

//in your loop
var first = reader[0].ToString();
var second = image.ToString();
//Suggestion made by KyleMit
var newLine = string.Format("{0},{1}", first, second);
csv.AppendLine(newLine);

//after your loop
File.WriteAllText(filePath, csv.ToString());

Or something to this effect.
My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.

You can replace

File.WriteAllText(filePath, csv.ToString());

with

File.AppendAllText(filePath, csv.ToString());

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

var newLine = $"{first},{second}"

EDIT

Here is a link to a question that explains what Environment.NewLine does.

How do I Create a CSV file in C#

You can write a csv file using streamwriter. Your file will be located in bin/Debug (if running debug mode and not stating otherwise).

 var filepath = "your_path.csv";
using (StreamWriter writer = new StreamWriter(new FileStream(filepath,
FileMode.Create, FileAccess.Write)))
{
writer.WriteLine("sep=,");
writer.WriteLine("Hello, Goodbye");
}

What is wrong with my writing data to a csv file in c#?

You just need to flush the stream. To achieve that, just use the using statement

using StreamWriter writer = new StreamWriter(newFileName);
writer.WriteLine("Score,Time");
for (int i = 0; i < 5; i++)
{
writer.WriteLine(scoresAndSeconds[i, 0].ToString() + "," + scoresAndSeconds[i, 1].ToString());
}

Note you might want to look at a Csv library for more extensive CSV support

C# write to csv file

Click here and copy the static class Extensions with the extension method toDate(...) I have written (don't forget to add using System.Globalization;).
If you're using it, you can do it simply like this, without having to catch an exception:

var arrayItems = from DataRow myrow in dt.Rows select row.ItemArray;
foreach (var array in arrayItems)
{
for (var i = 0; i < array.Length; i++)
{
var strItem = (array[i] ?? "").ToString();
var date=strItem.toDate("yyyy-MM-dd");
if (!date.HasValue) {
swOut.Write(strItem + ",");
}
else
{
swOut.Write(date.Value.Year + '-' +
date.Value.Month + '-' + date.Value.Day + ",");
}
}
swOut.WriteLine();
}

Note that if you have to match a different data format, just change the parameter in the funtion .toDate("yyyy-MM-dd"). You can even specify multiple data formats which are accepted, like so:

string[] dateFmt = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};

then inside the loop you can use it:

var date=strItem.toDate(dateFmt);

That way, they will be interpreted and parsed and then they will be converted into YYYY-MM-dd and written into the .csv file, as you have specified it in the Write statement of your for loop.

Write data into csv file

simply this:

    static void WriteTest()
{
// Write sample data to CSV file
using (CsvFileWriter writer = new CsvFileWriter(@"E:\SharedDoc1\WriteTest.csv"))
{
Random rnd = new Random();

for (int i = 0; i < 100; i++)
{
CsvRow row = new CsvRow();
for (int j = 0; j < 5; j++)
row.Add(rnd.NextDouble().ToString("0.000000")); //round to 6 decimal digits

writer.WriteRow(row);
}
}
}

the output is as following:

0.848731,0.525468,0.829536,0.397083,0.493102
0.398665,0.914157,0.768229,0.520031,0.249966
0.083535,0.409240,0.325824,0.177057,0.114989

Note that rnd.NextDouble() returns a double between 0 and 1, if you want larger numbers you should multiply it with your factor. For example if you want doubles up to 1000 do this:

row.Add((rnd.NextDouble() * 1000).ToString("0.0#####"));

write changes in a csv file with c#

As other people suggested here, it's true that the developer hasn't control over when the finalizer is called. The garbage collector decides when to free the memory.

But, you should look at Dispose. If you implement IDisposable, and dispose of your object, then the code in Dispose will run.

First of all, your class should implement the above interface

class Tabelle : IDisposable

Then you need to wrap your code from destructor with the Dispose() method.

public void Dispose()
{
string[] information = new string[liste.Count];
for (int i = 0; i < liste.Count; i++)
{
information[i] = liste[i].Number + ";" + liste[i].Name + ";" + liste[i].Salary;
}
File.WriteAllLines(@"data.txt", information);
GC.SuppressFinalize(this);
}

Also, don't forget to use using keyword when creating your class.

 using (Tabelle tab = new Tabelle())
{
foreach (Employees e in tab.getAll())
{
Console.WriteLine(e);
}

tab.updating(1, "fafdsdsf", 323);
}


Related Topics



Leave a reply



Submit