Removing a specific line from a text file in C# is a common task. Here are two methods: a straightforward approach and a more efficient LINQ-based solution.
Method 1: The Temporary File Method
This method creates a temporary file, copies the contents of the original file excluding the line to be removed, then replaces the original file. This is suitable for very large files where loading everything into memory could cause issues.
<code class="language-csharp">string tempFile = Path.GetTempFileName(); using (var reader = new StreamReader("file.txt")) using (var writer = new StreamWriter(tempFile)) { string line; while ((line = reader.ReadLine()) != null) { if (line != "removeme") // Replace "removeme" with your target line writer.WriteLine(line); } } File.Delete("file.txt"); File.Move(tempFile, "file.txt");</code>
Method 2: The LINQ Method (More Efficient for Smaller Files)
For smaller files, LINQ offers a more concise and potentially faster solution. It filters the lines to keep, then writes them back to the file. The key advantage is deferred execution – the file isn't processed until File.WriteAllLines
is called.
<code class="language-csharp">string tempFile = Path.GetTempFileName(); var linesToKeep = File.ReadLines("fileName").Where(l => l != "removeme"); // Replace "fileName" and "removeme" as needed File.WriteAllLines(tempFile, linesToKeep); File.Delete("fileName"); File.Move(tempFile, "fileName");</code>
Important Considerations:
try-catch
blocks) to manage potential exceptions like FileNotFoundException
.Remember to replace "file.txt"
and "removeme"
with your actual file path and the line you want to delete.
The above is the detailed content of How to Efficiently Delete a Line from a Text File in C#?. For more information, please follow other related articles on the PHP Chinese website!