C# 檔案
處理檔案
名稱空間 System.IO 中的 File 類,允許我們處理檔案
示例
using System.IO; // include the System.IO namespace
File.SomeFileMethod(); // use the file class with methods
File 類有許多有用的方法用於建立檔案和獲取有關檔案資訊。例如:
| 方法 | 描述 |
|---|---|
AppendText() |
將文字追加到現有檔案的末尾 |
Copy() |
複製檔案 |
Create() |
建立或覆蓋檔案 |
Delete() |
刪除檔案 |
Exists() |
測試檔案是否存在 |
ReadAllText() |
讀取檔案內容 |
Replace() |
用另一個檔案的內容替換檔案的內容 |
WriteAllText() |
建立一個新檔案並將內容寫入其中。如果檔案已存在,則會被覆蓋。 |
有關 File 方法的完整列表,請參閱 Microsoft .Net File 類參考。
寫入檔案並讀取它
在下面的示例中,我們使用 WriteAllText() 方法建立一個名為“filename.txt”的檔案並向其中寫入一些內容。然後我們使用 ReadAllText() 方法讀取檔案的內容。
示例
using System.IO; // include the System.IO namespace
string writeText = "Hello World!"; // Create a text string
File.WriteAllText("filename.txt", writeText); // Create a file and write the content of writeText to it
string readText = File.ReadAllText("filename.txt"); // Read the contents of the file
Console.WriteLine(readText); // Output the content
輸出將是:
Hello World!