Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto clear a textfile without deleting file?

Tags:

c#

.net

vb.net

Question: I have an ini file which I need to clear before I add info to it.

Unfortunately, if I just delete the file, the permissions are gone as well.

Is there a way to delete a file's content without deleting the file ?

like image 860
Stefan Steiger Avatar asked Dec 02 '22 04:12

Stefan Steiger


2 Answers

String path = "c:/file.ini";

using (var stream = new FileStream(path, FileMode.Truncate))
{
    using (var writer = new StreamWriter(stream))
    {
        writer.Write("data");
    }
}
like image 157
QrystaL Avatar answered Dec 03 '22 18:12

QrystaL


Just open the file in truncate (i.e. non-append) mode and close it. Then its contents are gone. Or use the shortcut in the My namespace:

My.Computer.FileSystem.WriteAllText("filename", "", False)
like image 40
Konrad Rudolph Avatar answered Dec 03 '22 18:12

Konrad Rudolph