Edit a Specific Line of a Text File in C#

Edit a specific Line of a Text File in C#

You can't rewrite a line without rewriting the entire file (unless the lines happen to be the same length). If your files are small then reading the entire target file into memory and then writing it out again might make sense. You can do that like this:

using System;
using System.IO;

class Program
{
static void Main(string[] args)
{
int line_to_edit = 2; // Warning: 1-based indexing!
string sourceFile = "source.txt";
string destinationFile = "target.txt";

// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}

if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);

// Read the old file.
string[] lines = File.ReadAllLines(destinationFile);

// Write the new file over the old file.
using (StreamWriter writer = new StreamWriter(destinationFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(lines[currentLine - 1]);
}
}
}
}
}

If your files are large it would be better to create a new file so that you can read streaming from one file while you write to the other. This means that you don't need to have the whole file in memory at once. You can do that like this:

using System;
using System.IO;

class Program
{
static void Main(string[] args)
{
int line_to_edit = 2;
string sourceFile = "source.txt";
string destinationFile = "target.txt";
string tempFile = "target2.txt";

// Read the appropriate line from the file.
string lineToWrite = null;
using (StreamReader reader = new StreamReader(sourceFile))
{
for (int i = 1; i <= line_to_edit; ++i)
lineToWrite = reader.ReadLine();
}

if (lineToWrite == null)
throw new InvalidDataException("Line does not exist in " + sourceFile);

// Read from the target file and write to a new file.
int line_number = 1;
string line = null;
using (StreamReader reader = new StreamReader(destinationFile))
using (StreamWriter writer = new StreamWriter(tempFile))
{
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
writer.WriteLine(line);
}
line_number++;
}
}

// TODO: Delete the old file and replace it with the new file here.
}
}

You can afterwards move the file once you are sure that the write operation has succeeded (no excecption was thrown and the writer is closed).

Note that in both cases it is a bit confusing that you are using 1-based indexing for your line numbers. It might make more sense in your code to use 0-based indexing. You can have 1-based index in your user interface to your program if you wish, but convert it to a 0-indexed before sending it further.

Also, a disadvantage of directly overwriting the old file with the new file is that if it fails halfway through then you might permanently lose whatever data wasn't written. By writing to a third file first you only delete the original data after you are sure that you have another (corrected) copy of it, so you can recover the data if the computer crashes halfway through.

A final remark: I noticed that your files had an xml extension. You might want to consider if it makes more sense for you to use an XML parser to modify the contents of the files instead of replacing specific lines.

Modify a specific line in a text file

Write the whole file again would be easier:

string old = "old string";
string nw =" new string";
int counter = 0;

Using(StreamWriter w =new StreamWriter("newfile");
foreach(string s in File.ReadLines(path))
{
if (s = old)
{
w. WriteLine(nw);
}
else
{
w. WriteLine(s);
}
counter ++;
}

C# Read text file line by line and edit specific line

You can store the contents in a StringBuilder like this:

StringBuilder sbText = new StringBuilder();
using (var reader = new System.IO.StreamReader(textFile)) {
while ((line = reader.ReadLine()) != null) {
if (line.Contains(stringToSearch)) {
//possibly better to do this in a loop
sbText.AppendLine(reader.ReadLine());
sbText.AppendLine(reader.ReadLine());

sbText.AppendLine("Your Text");
break;//I'm not really sure if you want to break out of the loop here...
}else {
sbText.AppendLine(line);
}
}
}

and then write it back like this:

using(var writer = new System.IO.StreamWriter(@"link\to\your\file.txt")) {
writer.Write(sbText.ToString());
}

Or if you simply want to store it in the string textFile you can do it like this:

textFile = sbText.ToString();

Replace String in Specific line in text file

Another approach with Linq

string[] file = File.ReadAllLines(@"c:\yourfile.txt");
file = file.Select((x, i) => i > 1 && i < 5 ? x.Replace("no", "number") : x).ToArray();
File.WriteAllLines(@"c:\yourfile.txt", file);

Best approach to replace specific lines in a text file in c#

I don't know what IO issue you are worried about, but your code should work ok. You can code more concisely as follows:

using (StreamReader sr = new StreamReader(@"S:\Personal Folders\A\TESTA.txt"))
{
using (StreamWriter sw = new StreamWriter(@"S:\Personal Folders\A\TESTB.txt"))
{
while ((string line = sr.ReadLine())!= null)
{
sw.WriteLine(line.Replace("before", "after"));
}
}
}

This will run a bit faster because it searches for "before" only once per line. By default the StreamWriter buffers your writes and does not flush to the disk each time you call WriteLine, and file IO is asynchronous in the operating system, so don't worry so much about IO.

How to update a specific value in a specific line of a text file c#

You need to rebuild your line collection with new values. YOu need to take it apart and re-assemble

foreach(string line in lines)
{
string[] items = line.Split(',');

if (items[2] == id.ToString())
{
items[0] = EditCategoryInput;
}
newLineList.Add(string.Join(',', items )); // add your new or unchanged line to new line collection
}

How can I read and replace Strings line by line in a Text File?

You can read the lines in individually:

string text = "";
using (StreamReader sr = new StreamReader("C:\\Users\\Donavon\\Desktop\\old.sql"))
{
int i = 0;
do
{
i++;
string line = sr.ReadLine();
if (line != "")
{
line = line.Replace("('',", "('" + i + "',");
text = text + line + Environment.NewLine;
}
} while (sr.EndOfStream == false);
}
File.WriteAllText("C:\\Users\\Donavon\\Desktop\\new.sql", text);


Related Topics



Leave a reply



Submit