I am reading a .txt file line by line and when the line in the file is "Hello1", I want to Replace that Line with "Hello2" but I dont get that to work.

I think I miss something out here

//Save this emailadress to the RouletteDataBase file
String Path = C:\\File.txt";

System.IO.FileStream sd2 = new System.IO.FileStream(Path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
System.IO.StreamReader ReadThis = new System.IO.StreamReader(sd2);

System.IO.FileStream sd3 = new System.IO.FileStream(Path, System.IO.FileMode.Open, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
System.IO.StreamWriter WriteThis = new System.IO.StreamWriter(sd3);




                String GetLine = "";
            

                while (ReadThis.Peek() >= 0) //Read this file
                {
                    GetLine = ReadThis.ReadLine(); //Get the String

                    if (GetLine != "")
                    {
                        if (GetLine == "Hello1")
                        {
                            WriteThis.WriteLine("Hello2"); //Replace 
                        }
                    }
                }
                sd2.Close(); //close file

You have to completely rewrite the file.

open original file for reading
open temp file for writing
while not end-of-input-file
   read a line from input file
   if this is the line to be replaced
        write new line to output file
   otherwise 
        write the line to the output file
end loop
close both files
delete original file
rename temp file with the name of the original file

Yes, I supposed I had to do something like that.. I could save all lines into a vector and replace the nessecary elements while writing to a new file.

/great

You have to completely rewrite the file.

open original file for reading
open temp file for writing
while not end-of-input-file
   read a line from input file
   if this is the line to be replaced
        write new line to output file
   otherwise 
        write the line to the output file
end loop
close both files
delete original file
rename temp file with the name of the original file

Yes, you could just read the entire input file into memory then rewrite it back to the original file. But ... what will you do with a huge file whose size is several gigs? Using a temp file like I described is the general method to do what you want because it works with files of any size without consuming too much memory.

Hi, I've been googleing this topic for hours today. What if you want to load the first text file into the memory since you will be replacing lines in it several times a second? How can I go about doing this?

This question has already been answered. Start a new discussion instead.