How can I clear the content of a file?

大兔子大兔子 提交于 2019-11-27 12:32:21

You can use the File.WriteAllText method.

System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);
Abhay Jain

This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.

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.
sajoshi

Use FileMode.Truncate everytime you create the file. Also place the File.Create inside a try catch.

The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.

Try using something like

File.Create

Creates or overwrites a file in the specified path.

Mohammad Albay

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);
     }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!