【发布时间】:2011-02-15 04:49:43
【问题描述】:
如何清除文件内容?
【问题讨论】:
如何清除文件内容?
【问题讨论】:
您可以使用File.WriteAllText 方法。
System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);
【讨论】:
File.WriteAllText,似乎有时(?)会删除文件,因为硬链接没有保持更新。
IO exceptions of file is in use,所以我建议你通过文件流手动处理它
我这样做是为了清除文件内容而不创建新文件,因为我不希望文件显示新的创建时间,即使应用程序刚刚更新了其内容。
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.
【讨论】:
每次创建文件时都使用FileMode.Truncate。还将File.Create 放在try catch 内。
【讨论】:
最简单的方法是:
File.WriteAllText(path, string.Empty)
但是,我建议你使用FileStream,因为第一个解决方案可以抛出UnauthorizedAccessException
using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
lock(fs)
{
fs.SetLength(0);
}
}
【讨论】:
【讨论】:
最简单的方法可能是通过您的应用程序删除文件并创建一个具有相同名称的新文件...更简单的方法是让您的应用程序用新文件覆盖它。
【讨论】: