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
Release: 2025-01-14 09:21:42
Original
988 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template