Home > Blockchain >  Add data to CSV if string is not found
Add data to CSV if string is not found

Time:05-18

I have an application that updates data within a CSV. What I am trying to add is, if the "name" is not in the CSV, then add it. I have tried changing the while to an if/then, but that gave me no results, just a blank line within the CSV.

Code:

using (StreamReader reader = new StreamReader(path))
{
    String line;

    while ((line = reader.ReadLine()) != null)
    {
        if (line.Split(',')[0].Equals("newName"))
        {
            String[] split = line.Split(',');
            split[1] = tPoints.ToString();
            line = String.Join(",", split);
        }
        lines.Add(line);
    }
}
using (StreamWriter writer = new StreamWriter(path))
{
    foreach (String line in lines)
        writer.WriteLine(line);
}

Current CSV Data:

name,734937

If item is NOT found, I am trying have it add a new row. So expected result would be something similar to below:

name,734937
newName,0 

CodePudding user response:

You can try something like this:

bool termFound = false;
string searchTerm = "newName";
var lines = new List<string>();

using (StreamReader reader = new StreamReader("input.csv"))
{
    string line;

    while ((line = reader.ReadLine()) != null)
    {
        lines.Add(line);

        if (line.Split(',')[0].Equals(searchTerm))
            termFound = true;
    }
}
using (StreamWriter writer = new StreamWriter("output.csv"))
{
    foreach (string line in lines)
        writer.WriteLine(line);

    if(termFound == false)
        writer.WriteLine($"{searchTerm},0");
}
  •  Tags:  
  • c#
  • Related