在 C# 中追加到文字檔案
本教程將討論在 C# 中追加文字檔案的方法。
在 C# 中使用 File.AppendAllText() 方法向文字檔案追加內容
C# 中的 File.AppendAllText() 方法用於開啟現有檔案,將所有文字附加到檔案末尾,然後關閉檔案。如果檔案不存在,則 File.AppendAllText() 方法將建立一個新的空檔案並將資料寫入其中。File.AppendAllText() 方法採用檔案路徑和要寫入的文字作為引數。以下程式碼示例向我們展示瞭如何使用 C# 中的 File.AppendAllText() 方法將資料追加到文字檔案中。
using System;
using System.IO;
namespace append_to_file {
class Program {
static void Main(string[] args) {
File.AppendAllText(@"C:\File\file.txt", "This is the new text" + Environment.NewLine);
}
}
}
執行程式碼前的 file.txt:
this is all the text in this file
執行程式碼後的 file.txt:
this is all the text in this file This is the new text
在上面的程式碼中,我們用 C# 中的 File.AppendAllText() 方法在路徑 C:\File 內的 file.txt 的末尾附加了文字 This is new text,並在 file.txt 檔案的末尾新增了新行。
在 C# 中使用 StreamWriter 類附加到文字檔案
我們可以通過 StreamWriter 類實現相同的目標。StreamWriter 類用於將文字寫入 C# 中的流或檔案。SreamWriter.WriteLine() 方法用 C# 編寫了整行。我們可以使用 File.AppendText() 方法初始化 StreamWriter 類的物件,以初始化 StreamWriter 類的例項,該例項會將資料附加到檔案中。以下程式碼示例向我們展示瞭如何使用 C# 中的 StreamWriter 類將資料追加到文字檔案的末尾。
using System;
using System.IO;
namespace append_to_file {
class Program {
static void Main(string[] args) {
using (StreamWriter sw = File.AppendText(@"C:\File\file.txt")) {
sw.WriteLine("This is the new text");
}
}
}
}
執行程式碼前的 file.txt:
this is all the text in this file
執行程式碼後的 file.txt:
this is all the text in this file This is the new text
在上面的程式碼中,我們使用 sw.WriteLine() 方法在文字 file.txt 的末尾附加了文字 This is new text 和新行。在 C# 中。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn