I have a problem: how can I delete a line from a text file in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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.
I wrote a method to delete lines from files.
This program uses
using System.IO
.See my code:
To remove an item from a text file, first move all the text to a list and remove whichever item you want. Then write the text stored in the list into a text file:
I extended what Markus Olsson suggested, and came up with this class that adds multiple search strings and a couple of event:
Usage:
For very large files I'd do something like this
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
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.
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.I'd very simply: