Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit a specific Line of a Text File in C#

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?

like image 334
Luis Avatar asked Dec 28 '09 19:12

Luis


People also ask

How do you overwrite a line in a file in C++?

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.

How do you delete a specific line in a file in C?

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.

What is file manipulation in C?

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.


1 Answers

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); 
like image 59
Bruce Afruz Avatar answered Oct 02 '22 15:10

Bruce Afruz