The*_*ter 118
您可以使用File.WriteAllText 方法.
System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);
Run Code Online (Sandbox Code Playgroud)
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)
最简单的方法是:
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)