Editing/Saving a row in a CSV file

29,309

Solution 1

Here is your solution using StreamReader class:

String path = @"C:\CSV.txt";
List<String> lines = new List<String>();

if (File.Exists(path));
{
    using (StreamReader reader = new StreamReader(path))
    {
        String line;

        while ((line = reader.ReadLine()) != null)
        {
            if (line.Contains(","))
            {
                String[] split = line.Split(',');

                if (split[1].Contains("34"))
                {
                    split[1] = "100";
                    line = String.Join(",", split);
                }
            }

            lines.Add(line);
        }
    }

    using (StreamWriter writer = new StreamWriter(path, false))
    {
        foreach (String line in lines)
            writer.WriteLine(line);
    }
}

If you want to overwrite the file, use this StreamWriter constructor with append = false.

Solution 2

Maybe somthing like this, you probably will need to clean it up and add some error handling, but it does the job

    string path = @"C:\\CSV.txt";

    string[] lines = File.ReadAllLines(path);
    for (int i = 0; i < lines.Length; i++)
    {
        string line = lines[i];
        if (line.Contains(","))
        {
            var split = line.Split(',');
            if (split[1].Contains("34"))
            {
                split[1] = "100";
                line = string.Join(",", split);
            }
        }
    }
    File.WriteAllLines(@"C:\\CSV.txt", lines);
Share:
29,309
KJSR
Author by

KJSR

C#, ASP.NET, MVC, MVP, WinForms, WebForms, ASP.NET Core, HTML, JQuery, JavaScript, AJAX, REST API

Updated on July 09, 2022

Comments

  • KJSR
    KJSR almost 2 years

    After following this topic I am able to create the new row but my question is how do I save or write the new line to the file?

    I tried 'StreamWriter' but it only writes the newly created line.

    Any suggestions please?

    Here is my code so far:

    string path = @"C:/CSV.txt";
    
    string[] lines = File.ReadAllLines(path);
    
    var splitlines = lines.Select(l => l.Split(','));
    
    foreach (var line in splitlines)
    {
       if(line[1].Contains("34"))
       {                                        
         line[1] = "100";
         var newline = string.Join(",", line);
         StreamWriter sr = new StreamWriter(path);    
         sr.WriteLine(newline);
         sr.Close();                                      
       }
     }
    
  • KJSR
    KJSR over 11 years
    Excellent solution Zarathos. Wasn't aware of the StreamWriter constructor. But now I know :) Thanks
  • Rajenthiran T
    Rajenthiran T about 7 years
    This is get value from grid and update the .CSV file process. If you guys have any doubt share with me. This is work fine.