I have a problem: how can I delete a line from a text file in C#?
The End of the File (EOF) indicates the end of input. After we enter the text, if we press ctrl+Z, the text terminates i.e. it indicates the file reached end nothing to read.
To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.
For very large files I'd do something like this
string tempFile = Path.GetTempFileName(); using(var sr = new StreamReader("file.txt")) using(var sw = new StreamWriter(tempFile)) { string line; while((line = sr.ReadLine()) != null) { if(line != "removeme") sw.WriteLine(line); } } File.Delete("file.txt"); File.Move(tempFile, "file.txt");
Update I originally wrote this back in 2009 and I thought it might be interesting with an update. Today you could accomplish the above using LINQ and deferred execution
var tempFile = Path.GetTempFileName(); var linesToKeep = File.ReadLines(fileName).Where(l => l != "removeme"); File.WriteAllLines(tempFile, linesToKeep); File.Delete(fileName); File.Move(tempFile, fileName);
The code above is almost exactly the same as the first example, reading line by line and while keeping a minimal amount of data in memory.
A disclaimer might be in order though. Since we're talking about text files here you'd very rarely have to use the disk as an intermediate storage medium. If you're not dealing with very large log files there should be no problem reading the contents into memory instead and avoid having to deal with the temporary file.
File.WriteAllLines(fileName, File.ReadLines(fileName).Where(l => l != "removeme").ToList());
Note that The .ToList
is crucial here to force immediate execution. Also note that all the examples assume the text files are UTF-8 encoded.
Read the file, remove the line in memory and put the contents back to the file (overwriting). If the file is large you might want to read it line for line, and creating a temp file, later replacing the original one.
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