Click to See Complete Forum and Search --> : C# Help! Anyone know how to clear a text file?


Zeak
May 21st, 2009, 01:07 PM
Hi all,

I just need to know how to clear everything in a text file using c++.

I tried deleting it, with File.Delete(Patch + navn + ".txt");
but all the content got saved into another text file :S... So i think I should clear the .txt file before deleting it. Anyone know how to do in c#?


Thanks.

BigEd781
May 21st, 2009, 01:11 PM
Hi all,

I just need to know how to clear everything in a text file using c++.

I tried deleting it, with File.Delete(Patch + navn + ".txt");
but all the content got saved into another text file :S... So i think I should clear the .txt file before deleting it. Anyone know how to do in c#?


Thanks.

You say you need an answer in C++, but it looks like your code is in C#. Which one is it? If it is C#, File.Delete works as you would expect, it does not copy the file before deleting it.

Zeak
May 21st, 2009, 01:15 PM
Im using C# sorry,

I did file.delete then after the textfile got deleted, I have a code to create a new textfile, but the content of the deleted text file is save/appended to the new textfile.

So i was wondering if anyone know how to clear text file with C#. My solution is to clear text it before deleting it.

vodien
May 21st, 2009, 02:10 PM
Hi Zeak,

The way I code it is to replace the existing texts with blanks or delete all the texts.

Vo Duc Dien

Zeak
May 21st, 2009, 02:20 PM
Hi Zeak,

The way I code it is to replace the existing texts with blanks or delete all the texts.

Vo Duc Dien

But how would you code this in c#? How to replace the existing text with blanks in a textfile?

BigEd781
May 21st, 2009, 03:59 PM
This will do what you want. You need to open the stream using FileMode.Create, which will create a new file, or write over an existing one. So, assuming that "C:\test.txt" already exists and is filled with some text, this will have the same effect as deleting all of that text.


using ( FileStream stream = new FileStream( @"C:\test.txt", FileMode.Create ) )
using ( TextWriter writer = new StreamWriter( stream ) )
{
writer.WriteLine( "" );
}

Zeak
May 21st, 2009, 04:31 PM
Thx BigEd, and everyone else who helped!

Problem solved! :)

memeloo
May 22nd, 2009, 07:57 AM
using ( FileStream stream = new FileStream( @"C:\test.txt", FileMode.Create ) )
using ( TextWriter writer = new StreamWriter( stream ) )
{
writer.WriteLine( "" );
}

cool, thx, I didn't know that it's possible to write multiple usings