Home > Mobile >  How to remove a line from csv file if it contains a specific word
How to remove a line from csv file if it contains a specific word

Time:03-28

I am trying to remove a line from csv file if it contains the word. But instead, it deletes everything inside CSV. You can find my code attached below. I am more or less sure that my for loop is incorrect but I couldn't make any other logic.

[HttpPost("Delete{studentIndex}")]
        public IActionResult DeleteStudent([FromRoute] string studentIndex)
        {
            string[] values = System.IO.File.ReadAllLines("data.csv");
            StreamWriter Writer = new StreamWriter("data.csv", false);
            
            for (int i = 0; i < values.Length; i  )
            {
                if (values[i].Contains(studentIndex))
                {
                    Writer.WriteLine(values[i].Replace(values[i], ""));
                }
            }

            Writer.Close();

            return Ok();
        }

CodePudding user response:

Your code only writes lines that contain studentIndex, and on those lines it replaces them with a blank. This is why your output is empty.

If the line contains student index, don't write it. There's no need for any string replacement

if (!values[i].Contains(studentIndex))
{
    Writer.WriteLine(values[i]);
}

If you're trying to write idiomatic c#, the code could be simplified:

var values = System.IO.File.ReadAllLines("data.csv");
using (var writer = new StreamWriter("data.csv", false) 
{
    values.Where(v => !v.Contains(student index))
          .Select(writer.WriteLine);
}        
return Ok();
  • Related