tags:

views:

92

answers:

4

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 ?

+5  A: 

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)
Konrad Rudolph
if he is going to be adding new data to in anywho, why not just write to the file in truncate mode? "I have an ini file which I need to clear before I add info to it." - OP
Adkins
Correct Way +1 for this
saurabh
@Adkins: only the OP can answer this. That he asked the question suggests that he’s using an API to write the INI file which uses append mode internally – weird, admittedly.
Konrad Rudolph
Good comment from **Adkins**. If you want to do it all in one go (just overwrite the content with new directly), see [QrystaL](http://stackoverflow.com/questions/3957709/howto-clear-a-textfile-without-deleting-file/3957790#3957790)s answer for a good approach.
awe
+1  A: 

This should probably work:

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

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

Pieter
+2  A: 

I'm not 100% sure, but you can try this:

File.WriteAllText( filename, "");

I'm not sure if this will delete, and recreate the file (in that case your permission problem will persist, or if it will clean out the file. Try it!

Øyvind Bråthen
+2  A: 
    String path = "c:/file.ini";
    using (var stream = new FileStream(path, FileMode.Truncate))
    {
        using (var writer = new StreamWriter(stream))
        {
            writer.Write("data");
        }
    }
QrystaL
Note that this approach is best for you to use if you have all the code for writing the new content inside the same method. If you have the deleting functionality and the writing of the new content in separate methods, you should use any of the other answers instead.
awe
Why would you use this instead of "using (var writer = File.CreateText(path)) { writer.Write("data"); }"?
Pieter
In your case if file doesn't exist it is created. We don't know if it is valid for topic-starter. I used general example that can be adapted appropriately.
QrystaL