How can I clear the content of a file?

后端 未结 6 1765
慢半拍i
慢半拍i 2020-12-02 21:48

I need to clear the contents of a particular file every time the applications starts. How do I do it?

6条回答
  •  执念已碎
    2020-12-02 22:32

    The easiest way is:

    File.WriteAllText(path, string.Empty)
    

    However, I recommend you use FileStream because the first solution can throw UnauthorizedAccessException

    using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
    {
         lock(fs)
         {
              fs.SetLength(0);
         }
    }
    

提交回复
热议问题