-3

how to Shift text file rows by one after deleting a particular line based on condition xyz=true for that particular line. I want to use C#.

 using (StreamWriter writer = new StreamWriter(file))
        {

            while ((line = rows[rowIndex++]) != null)
            {
            if( line contains xyz )// i know the logic to find this;
               {
                  delete this line and shift all below lines one up;
                 }
                 }
           }
swifty
  • 165
  • 1
  • 1
  • 17
  • The safe way of doing this is writing undeleted lines to a temporary file and, if everything worked, swap the temporary file with the original then delete the old file. [Here is an example](https://stackoverflow.com/questions/324670/). Not doing this can corrupt your file if you get an IO error partway through the change. – Dour High Arch Feb 05 '18 at 17:12
  • `File.WriteAllLines(filePath, File.ReadAllLines(filePath).Where(line => !line.Contains("xyz")));` (this should work, but consider @DourHighArch comment about safely dealing with I/O errors) – Rufus L Feb 05 '18 at 17:40

1 Answers1

0

A simple way to do this for small files (files which can be completely loaded into memory) is to use File.ReadAllLines() to get a string[] of the lines. With this, you can loop through the array of strings and test each one to determine if it should be written to the new file or not.

A similar question came up recently here C# Delete line i text file if it is different than specific term

If you're writing the output to a new file, you don't need to worry about moving all the later lines up, removing the entire line will also remove the line ending characters.

Hope this helps

Trevor
  • 1,251
  • 1
  • 9
  • 11