簡體   English   中英

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

[英]Clearing content of text file using C#

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

File.WriteAllText(path, String.Empty);

或者,

File.Create(path).Close();

只需打開帶有FileMode.Truncate標志的文件,然后關閉它:

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]);

當 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();
}

您可以使用始終流編寫器。它每次都會刪除舊數據並附加新數據。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM