Home >Backend Development >C++ >How to Efficiently Delete Lines from Text Files in C#?

How to Efficiently Delete Lines from Text Files in C#?

DDD
DDDOriginal
2025-01-14 09:21:421020browse

How to Efficiently Delete Lines from Text Files in C#?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn