How to efficiently delete text file lines in C#
Deleting specific lines from a text file is a common task in programming. For large files, an efficient approach in C# is to create a temporary file and rewrite the contents of the original file into the temporary file while excluding unnecessary lines. The following code demonstrates this approach:
<code class="language-csharp">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");</code>
However, for smaller text files, a simpler, direct execution and less memory intensive approach is preferable:
<code class="language-csharp">File.WriteAllLines(fileName, File.ReadLines(fileName).Where(l => l != "removeme").ToList());</code>
It is important to note that all examples assume that the text file uses UTF-8 encoding.
The above is the detailed content of How to Efficiently Delete Lines from Text Files in C#?. For more information, please follow other related articles on the PHP Chinese website!