C#
File Handling
Text File
Programming
Code Example

Clearing content of text file using C

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In C#, the simplest way to clear the contents of a text file is to overwrite it with an empty string. If you need lower-level control, you can also truncate the file stream directly, but for most applications File.WriteAllText(path, string.Empty) is the clearest answer.

Overwrite the File with an Empty String

The highest-level solution is:

csharp
using System.IO;

File.WriteAllText("log.txt", string.Empty);

This keeps the file itself but removes its contents.

It is usually the best choice when the goal is readability and the file is ordinary text.

Truncate the File with FileStream

If you want explicit control over the file length, truncate it.

csharp
1using System.IO;
2
3using (var stream = new FileStream("log.txt", FileMode.Open))
4{
5    stream.SetLength(0);
6}

This is functionally similar for the clearing use case, but it exposes the truncation operation directly.

Know the Difference Between Clearing and Deleting

Clearing a file means preserving the file path and leaving an empty file behind. Deleting a file removes the file entry itself.

That distinction matters when another part of the program expects the file to continue existing after reset.

Be Mindful of Open Handles

If another process or stream is holding the file open, clearing it may fail depending on how the file was opened and shared. When file operations behave unexpectedly, active handles and sharing mode are often the real problem.

Common Pitfalls

  • Deleting the file when the real requirement was to keep an empty file in place.
  • Using more complex stream code when a single WriteAllText call would be clearer.
  • Forgetting that another process may still have the file open.
  • Assuming truncation automatically recreates a missing file when the file does not exist.
  • Treating text-file clearing and log-rotation requirements as though they were the same task.

Summary

  • 'File.WriteAllText(path, string.Empty) is the clearest way to clear a text file in C#.'
  • 'FileStream.SetLength(0) is a good lower-level truncation option.'
  • Clearing preserves the file; deleting does not.
  • Open handles can prevent the operation from succeeding.
  • Choose the simplest approach that matches the actual file lifecycle you need.

Course illustration
Course illustration

All Rights Reserved.