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?
String path = "c:/file.ini"; using (var stream = new FileStream(path, FileMode.Truncate)) { using (var writer = new StreamWriter(stream)) { writer.Write("data"); } }
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
My.Computer.FileSystem.WriteAllText("filename", "", False)
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!
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.