Search code examples
c#-4.0filestream

How to overwrite the last line of text file


FileStream files = new FileStream("text.txt", FileMode.Append, FileAccess.Write);                       
StreamWriter cmdswriter = new StreamWriter(files);
cmdswriter.Write("last line content");

Solution

  • If your file is not too large:

    string path = "text.txt";
    var fileContent = File.ReadLines(path).ToList();
    
    fileContent[fileContent.Count - 1] = "last line content";
    File.WriteAllLines(path, fileContent);