How to clear file content?!

  • Thread starter Thread starter Guest
  • Start date Start date
Okay, I'm going to have to guess what you mean by "clear a text file." From
the context of your message, it sounds like you mean to remove all the text
from it. Now, there are several ways to do this, but all of them involve
what you refer to as "deleting and creating a new (empty) file." That is, if
you have a text file, and you want to remove the text from it, and then save
it, this is what happens in either case:

1. Open the file, remove the text from it by setting it to "" and then save
it. When you re-save it, you are essentially overwriting the existing file
with a new one.
2. Create a new file with no text in it and save it over the original. When
you save it, you are essentially overwriting the existing file with a new
one.

The bottom line is, when you save a file, you are writing it to the disk. If
it is an existing file, you are simply *over*writing it to the disk.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 
How can I clear a text file without deleting and creating a new (empty) file?

You can truncate a file by calling Stream.SetLength() on a FileStream.


Mattias
 
I found a simple solution on MSDN:

using (StreamWriter sw = new StreamWriter(fileToClear))
{
sw.Write("");
}

Very simple but it did what I want to!
 
Back
Top