C# Line by Line check of a file

473 views Asked by At

I am reading from a file line by line and i want to edit some of the lines i read.. The lines i want to edit must have some other specific lines above or below them, but i dont know how to express that in C#. For example:

http://www.youtube.com
You Tube | Music | something
Sports
Music
Radio
Clips
http://www.youtube.com/EDIT ME   
Sports
Music
Radio
Clips

and i want to edit a line only if next line is

Sports 

and the previous line is

Clips

So the only line i want to edit from the example above is

http://www.youtube.com/EDIT ME 

Any ideas?

3

There are 3 answers

0
Jon Skeet On

You can't really "edit" a file line by line. It would be best to take one of two approaches:

  • Read the whole file into memory, e.g. using File.ReadAllLines, then make appropriate changes in memory and rewrite the whole thing (e.g. using File.WriteAllLines)
  • Open both the input file and output file at the same time. Read a line at a time, work out what it should correspond to in the output file, then write the line.

The first version is simpler, but obviously requires more memory. It's particularly tricky if you need to look at the next and previous line, as you mentioned.

Simple example of the first approach:

string[] lines = File.ReadAllLines("foo.txt");
for (int i = 1; i < lines.Length - 1; i++)
{
    if (lines[i - 1] == "Clips" && lines[i + 1] == "Sports")
    {
        lines[i] = "Changed";
    }
}
File.WriteAllLines("foo.txt", lines);
0
Josh Maag On

If the file isn't that large, I would read in the entire file as a string. Then you can freely manipulate it using methods like indexOf and substring.

Once you have the string how you need it, write it back over the file you had.

0
Binary Worrier On

Approach #1
While you're looping through the file, keep a variable for the the previous line (always update this to the current line before you loop). Now you know the current line and previous line, you can decide if you need to edit the current line.

Approach #2
While you're looping through the file, set a flag corresponding to some condition e.g. I've just found Sports. If you later find a condition that should unset the flag e.g. I've just found Radio, un set it. If you find Clips you can check is the SportsFlag set to see if you need to edit this Clips line.

The second approach is more flexible (allows you to set and unset multiple flags depending on the current line) and and is good if there could be multiple lines of crud between Sports and Clips. It's effectively a poor mans State Machine