How to clear a text file without deleting the file?

Question: I have an ini file that I need to clear before adding information to it.

Unfortunately, if I just delete the file, the permissions will also disappear.

Is there a way to delete the contents of a file without deleting the file?

+4
source share
4 answers
String path = "c:/file.ini"; using (var stream = new FileStream(path, FileMode.Truncate)) { using (var writer = new StreamWriter(stream)) { writer.Write("data"); } } 
+7
source

Just open the file in truncation mode (that is, without adding) and close it. Then its contents disappeared. Or use a shortcut in the My namespace:

 My.Computer.FileSystem.WriteAllText("filename", "", False) 
+5
source

I am not 100% sure, but you can try the following:

 File.WriteAllText( filename, ""); 

I'm not sure if this will delete and re-create the file (in this case your problem will be resolved or if it clears the file. Try it!

+4
source

This should probably work:

 using (File.Create("your filename")); 

Here usage does not have a block due; at the end of the line. The .Create file truncates the file itself, and using it closes it immediately.

+3
source