使用 C # 清除文本文件的内容

如何使用 C # 清除文本文件的内容?

146111 次浏览
File.WriteAllText(path, String.Empty);

或者,

File.Create(path).Close();

只要打开带有 FileMode 截断标志的文件,然后关闭它:

using (var fs = new FileStream(@"C:\path\to\file", FileMode.Truncate))
{
}
 using (FileStream fs = File.Create(path))
{


}

将创建或覆盖文件。

另一个简短的说法是:

System.IO.File.WriteAllBytes(path, new byte[0]);

您可以一直使用流写入器。它将删除旧数据并且每次添加一个新数据。

using (StreamWriter sw = new StreamWriter(filePath))
{
getNumberOfControls(frm1,sw);
}

在 StreamWriter 中,当 append 设置为 false 时,只需写入文件 string.Empty。我认为这个对于初学者来说是最容易理解的。

private void ClearFile()
{
if (!File.Exists("TextFile.txt"))
File.Create("TextFile.txt");


TextWriter tw = new StreamWriter("TextFile.txt", false);
tw.Write(string.Empty);
tw.Close();
}

您可以清除文件的内容,就像在文件中写入内容一样,但将文本替换为“”

File.WriteAllText(@"FilePath", "");