Search code examples
c#visual-studio-2010filefilestream

read file and write text when find the line


I have a file with many rows. I read it in line by line and finding a specific string, I need to insert another line after this.

google -Source file facebook

google -the file which should I get stasckoverflow facebook

using (var fs = File.Open(fileOutPath, FileMode.OpenOrCreate))
        {
                using (StreamReader sr = new StreamReader(fs))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        if (line.StartsWith("google"))
                        {

what should I do to write "stasckoverflow" in the following line


Solution

  • You can't easily read and write lines from and to a text file simultaneously.

    You should solve this problem by creating a new temporary file with the data you want, and then deleting the old file and renaming the temp file to have the same name as the original file.

    Something along these lines should work (assuming that filePath is the original file):

    string tempPath = Path.GetTempFileName();
    
    using (var writer = new StreamWriter(tempPath))
    {
        foreach (string line in File.ReadLines(filePath))
        {
            writer.WriteLine(line);
    
            if (line.StartsWith("google"))
                writer.WriteLine("StackOverflow");
        }
    
        // If you want to add other lines to the end of the file, do it here:
    
        writer.WriteLine("This line will be at the end of the file.");
    }
    
    File.Delete(filePath);
    File.Move(tempPath, filePath); // Rename.
    

    If you ONLY want to write to the end of the file without inserting any text before the end of the file, you can do it without using a temporary file as follows:

    using (var writer = new StreamWriter(tempPath, append:true))
    {
        writer.WriteLine("Written at end of file, retaining previous lines.");
    }