Click here to Skip to main content
15,906,097 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
How can i read and write a text file at the same time.

I have the following code but the problem is that it does writes at the end of the file contents. but i want it to write at after "two". i.e. if the read line contains "two" then write "test" after "two".

FileStream fsrw = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fsrw);
StreamWriter sw = new StreamWriter(fsrw);
test = "Dummy";

 while (test != null)
{
 if (test.Contains("two"))
    {
    sw.Write("test");
    }
    test = sr.ReadLine();
}
sw.Close();
}
Posted
Updated 13-Aug-23 18:55pm

Reading a file that is being edited at the same time sounds like a really bad idea.

I'm afraid you could get unexpected results and impossible-to-find bugs...

Imagine the following scenario:

StreamWriter writes data to the end of the stream by default so the word "test" would most probably appear at the end of the file. Maybe it is possible to force StreamWriter to start writing at an arbitrary location, but that would not solve the whole problem... You would have to keep track of the current position, which is pretty difficult considering the fact that the file is changing in time. And don't forget that both StreamReader and StreamWriter use buffers to load/write data efficiently, which is adds even more complexity...

I suggest reading the entire file first, perform the changes and then write the file (or, if speed is important, perform the changes on the fly while reading or writing). If the file is too large, use a temporary file, but do not read and write at the same time...
 
Share this answer
 
Comments
KulaGGin 27-Nov-23 9:41am    
"Reading a file that is being edited at the same time sounds like a really bad idea."

It's not a bad idea. A perfectly valid use case: encrypting file in-place with AES using streams, so that you can encrypt big files and it's all good and well.

"I'm afraid you could get unexpected results and impossible-to-find bugs..."

No. That's wrong. You just write your code against the Stream, StreamReader and StreamWriter classes and you do TDD, so everything is tested, and then you also apply good software engineering practices, such as Clean Code, Clean Architecture, DDD, SOLID principles, GRASP principles, etc. Then you don't get unexpected results and bugs: everything is well-engineered and tested, and everything just works.
As mentioned by Kubajzz, reading a file that is being edited at the same time may have the possibility of yielding unexpected results.

If you wish to edit files as they are being edited, your best bet is to use FileSystemWatcher class:

C#
using System;
using System.IO;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string filePath = "full_path_to_your_file.txt";

        // NOTE: There is `FileSystemWatcher(DirectoryPath, Filter)` constructor as well
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = Path.GetDirectoryName(filePath);
        watcher.Filter = Path.GetFileName(filePath);

        // Callback when file is last written (aka, on file saved).
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Changed += OnFileChanged;

        watcher.EnableRaisingEvents = true;

        Console.WriteLine("Press Enter to exit.");
        Console.ReadLine();
    }

    private static void OnFileChanged(object sender, FileSystemEventArgs e)
    {
        string filePath = e.FullPath;

        try
        {
            // Read the entire content, manipulate, then dump back.
            string fileContent = File.ReadAllText(filePath);
            string updatedContent = StringManipulationStuff(fileContent);

            File.WriteAllText(filePath, updatedContent);
        }
        catch (Exception ex)
        {
            // Error handle...
        }
    }

    private static string StringManipulationStuff(string input)
    {
        string pattern = @"\btwo\b";
        string replacement = "twotest";

        return Regex.Replace(input, pattern, replacement);
    }
}
 
Share this answer
 
Comments
Graeme_Grant 14-Aug-23 0:57am    
you do realize this is a 13 year old question? Please focus on more current questions.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900