Writing data into CSV file in C#

后端 未结 15 1312
清酒与你
清酒与你 2020-11-22 17:15

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.         


        
15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 17:34

    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.

提交回复
热议问题