简体   繁体   中英

write back to first line of csv in c#

so I want to write some values to a csv file in 3 columns as follows:

number of series      firstVal       secondVal
10                    23             33
50                    55             66
100                   98             102

I stores all myvalues in a dictionary

var timeResults = new Dictionary<string, Dictionary<string, double>>();

and the mycode is like this:

 foreach (var resultSet in timeResults)
     {
     var csv = new StringBuilder();

     csv.AppendLine(String.Format("Number of TimeSeries;{0}", n));
     foreach (var result in resultSet.Value)
       {

       csv.AppendLine(String.Format("{0}.{1} (ms);{2}", resultSet.Key, result.Key, result.Value));

       }

     File.AppendAllText(@"D:/CSV/Results_" + resultSet.Key + ".csv", csv.ToString());

}

but What I get is something like this:

Number of TimeSeries        10
add.firstVal(ms)            74
add.secondVal (ms)          12
Number of TimeSeries        50
add.firstVal (ms)           4
add.secondVal(ms)           3
Number of TimeSeries        100
add.firstVal (ms)           6
add.secondVal (ms)          6

All I want to do is to tell it to go to first line but next column and write again. so all values would be in one column. how is it possible?

Writing and reading CVS files is not simple task by itself. It is better to use a libraris like CsvHelper and A Fast CSV Reader

Also, the dictionary does not guarantee the order in which you get records. It might be a problem for you. Consider using List instead or sort records by some criteria.

So, you code could be like this

        stream = new MemoryStream();
        writer = new StreamWriter(stream);
        csvWriter = new CsvWriter(writer);            
        csvWriter.Configuration.QuoteAllFields = false;
        csvWriter.Configuration.HasHeaderRecord = true;
        csvWriter.WriteField("Number of TimeSeries");
        csvWriter.WriteField("add.firstVal(ms)");
        csvWriter.WriteField("add.secondVal (ms)");
        csvWriter.NextRecord();
        foreach (var resultSet in timeResults)
        {
           csvWriter.WriteField(resultSet.Key);
           foreach (var result in resultSet.Value)
           {

              csvWriter.WriteField(result.Key);
              csvWriter.WriteField(result.Value));  
           }    
           csvWriter.NextRecord();
         }
        writer.Flush();
       // do what you need with the data in the stream.
       // dispose objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM