Is there any way to overwrite a certain string (let's say the string from line 6) from a file, without creating a new text file?
CodePudding user response:
You can write a method like this to update a line of an existing txt file ;
public void OverwriteLine(string newText, string filePath, int lineNumber)
{
string[] allLines = File.ReadAllLines(filePath);
allLines[lineNumber - 1] = newText;
File.WriteAllLines(filePath, allLines);
}
CodePudding user response:
You can do it using File.ReadAllLines()
and File.WriteAllLines()
,
var path = @"c:\text.txt"; //Your file Path
var allLines = File.ReadAllLines(path); //Read all data line by line.
allLines[5] = "Updated data"; //Update 6th line data
File.WriteAllLines(path, allLines); //Re-write the content.