Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a line from a text file in C#?

Tags:

c#

text-files

I have a problem: how can I delete a line from a text file in C#?

like image 621
alinpopescu Avatar asked Mar 21 '09 07:03

alinpopescu


People also ask

How does EOF work 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.

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

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.


2 Answers

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.

like image 199
Markus Olsson Avatar answered Sep 28 '22 01:09

Markus Olsson


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.

like image 41
Sascha Avatar answered Sep 28 '22 01:09

Sascha