Search code examples
c#replacestreamstreamreaderstreamwriter

Replace value & save file during reading CSV file (C#)


I'm reading csv file:

string line;

StreamReader sr = new StreamReader(file.ToString());

while ((line = sr.ReadLine()) != null)
{
    string col1 = line.Split(',')[10]; //old value
    col1 = "my value"; //new value
}

sr.Close();
sr.Dispose();

I want to replace old value by the new.

Then I need to save the file with the changes.

How can I do that?


Solution

  • I suggest using File class instead of Streams and Readers. Linq is very convenient when querying data:

    var modifiedData = File
      .ReadLines(file.ToString())
      .Select(line => line.Split(',')) 
      .Select(items => {
         //TODO: put relevant logic here: given items we should return csv line
         items[10] = "my value";
    
         return string.Join(",", items);
       })
      .ToList(); // <- we have to store modified data in memory
    
    File.WriteAllLines(file.ToString(), modifiedData);
    

    Another possibility (say, when initial file is too long to fit memory) is to save the modified data into a temporary file and then Move it:

     var modifiedData = File
      .ReadLines(file.ToString())
      .Select(line => line.Split(',')) 
      .Select(items => {
         //TODO: put relevant logic here: given items we should return csv line
         items[10] = "my value";
    
         return string.Join(",", items);
       });
    
     string tempFile = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.tmp");
    
     File.WriteAllLines(tempFile, modifiedData);
    
     File.Delete(file.ToString());
     File.Move(tempFile, file.ToString());