Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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();
        }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading