I have two text files, Source.txt and Target.txt. The source will never be modified and contain N lines of text. So, I want to delete a specific line of text in Target.txt, and replace by an specific line of text from Source.txt, I know what number of line I need, actually is the line number 2, both files.
I haven something like this:
string line = string.Empty; int line_number = 1; int line_to_edit = 2; using StreamReader reader = new StreamReader(@"C:\target.xml"); using StreamWriter writer = new StreamWriter(@"C:\target.xml"); while ((line = reader.ReadLine()) != null) { if (line_number == line_to_edit) writer.WriteLine(line); line_number++; }
But when I open the Writer, the target file get erased, it writes the lines, but, when opened, the target file only contains the copied lines, the rest get lost.
What can I do?
The only way to replace text in a file, or add lines in the middle of a file, is to rewrite the entire file from the point of the first modification. You cannot "make space" in the middle of a file for new lines.
An algorithm is given below to explain the C program to remove a line from the file. Step 1 − Read file path and line number to remove at runtime. Step 2 − Open file in read mode and store in source file. Step 3 − Create and open a temporary file in write mode and store its reference in Temporary file.
The content available on a file isn't volatile like the compiler memory in C. But the program can perform various operations, such as creating, opening, reading a file, or even manipulating the data present inside the file. This process is known as file handling in C.
the easiest way is :
static void lineChanger(string newText, string fileName, int line_to_edit) { string[] arrLine = File.ReadAllLines(fileName); arrLine[line_to_edit - 1] = newText; File.WriteAllLines(fileName, arrLine); }
usage :
lineChanger("new content for this line" , "sample.text" , 34);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With