Getting the next line of a file or writing to the previous line in C#

448 views Asked by At

Is it possible to either see what the next line of a file is or write to the previous line of a file?

I am reading through a roughly 13,000 line file and if a line matches one of my regular expressions I then change the line, if not, it stays the same. These lines are getting written to a new file. It looks like this, roughly of course.

//create Streamreader sr
//create Streamwriter sw
//loop through file by line
//if line matches REGEX, change it. Else, don't change it
//write line to new file
//if end of file, close sr and sw

I need to either look to the next for ENDREC so I can write a new line before it

OR if the current line is ENDREC I need to write to the line before it. Any ideas?

2

There are 2 answers

0
Erik On

How about something like this?

        var regex = new Regex(@"[a-zA-Z0-9_]+", RegexOptions.Compiled);

        using (var reader = File.OpenText("in.txt"))
        using (var writer = File.CreateText("out.txt"))
        {
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var match = regex.Match(line);

                if (match.Success)
                {
                    // Alter the line however you wish here.
                }

                writer.WriteLine(line);
            }
            writer.Flush();
        }
0
Michael McGriff On

If loading the whole file into memory isn't a problem, try something like this:

public void Test()
{
    string fileName = "oldFileName";
    string newFileName = "newFileName";
    string[] allLines = File.ReadAllLines(fileName);
    string changedLine = "Changed";
    var changedLines = allLines.Select(p => ((Regex.IsMatch(p, "test")) ? changedLine : p));
    File.WriteAllLines(newFileName, changedLines);
}