开发者

Howto clear a textfile without deleting file?

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 ?


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 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)


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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜