如何清除文件内容?

oli*_*ive 71 .net c# file clear

每次应用程序启动时,我都需要清除特定文件的内容.我该怎么做?

The*_*ter 118

您可以使用File.WriteAllText 方法.

System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);
Run Code Online (Sandbox Code Playgroud)

  • 如果在此操作之后另一个操作将访问该文件,我建议您不要这样做。我遇到了在这行代码之后文件没有关闭写入的问题,并导致“文件的 IO 异常正在使用中”,因此我建议您通过文件流手动处理它 (2认同)

Abh*_*ain 76

这就是我在不创建新文件的情况下清除文件内容的方法,因为即使应用程序刚刚更新了内容,我也不希望文件显示新的创建时间.

FileStream fileStream = File.Open(<path>, FileMode.Open);

/* 
 * Set the length of filestream to 0 and flush it to the physical file.
 *
 * Flushing the stream is important because this ensures that
 * the changes to the stream trickle down to the physical file.
 * 
 */
fileStream.SetLength(0);
fileStream.Close(); // This flushes the content, too.
Run Code Online (Sandbox Code Playgroud)

  • +1这是首先获取文件锁定,安全检查文件属性并最终清除内容的唯一方法. (5认同)
  • 在using块中创建文件流是否明智?那也将自动关闭流。 (2认同)

小智 11

使用FileMode.Truncate每次你创建的文件.也放在File.Create里面try catch.


Moh*_*bay 5

最简单的方法是:

File.WriteAllText(path, string.Empty)
Run Code Online (Sandbox Code Playgroud)

但是,我建议您使用,FileStream因为第一个解决方案可能会抛出UnauthorizedAccessException

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