Reputation: 279
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?
Upvotes: 0
Views: 484
Reputation: 51719
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
Upvotes: 2
Reputation: 643
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.
Upvotes: 1
Reputation: 1503519
You can't really "edit" a file line by line. It would be best to take one of two approaches:
File.ReadAllLines
, then make appropriate changes in memory and rewrite the whole thing (e.g. using File.WriteAllLines
)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);
Upvotes: 6