文件讀取和寫入是計算機程序中常見的操作,用于從文件中讀取數據或將數據寫入文件。在C#中,使用System.IO
命名空間中的類來進行文件讀寫操作。本文將詳細介紹如何在C#中進行文件讀取和寫入,包括讀取文本文件、寫入文本文件、讀取二進制文件和寫入二進制文件等操作。
1. 讀取文本文件
要讀取文本文件,可以使用StreamReader
類。以下是一個讀取文本文件的示例:
using System;
using System.IO;class Program
{static void Main(string[] args){string filePath = "sample.txt";try{using (StreamReader reader = new StreamReader(filePath)){string content = reader.ReadToEnd();Console.WriteLine("文件內容:");Console.WriteLine(content);}}catch (FileNotFoundException){Console.WriteLine("文件不存在:" + filePath);}catch (Exception ex){Console.WriteLine("發生異常:" + ex.Message);}}
}
在上述示例中,我們使用StreamReader
打開文件并使用ReadToEnd
方法讀取整個文件內容。通過using
語句,確保在使用完StreamReader
后自動釋放資源。
2. 寫入文本文件
要寫入文本文件,可以使用StreamWriter
類。以下是一個寫入文本文件的示例:
using System;
using System.IO;class Program
{static void Main(string[] args){string filePath = "output.txt";try{using (StreamWriter writer = new StreamWriter(filePath)){writer.WriteLine("Hello, world!");writer.WriteLine("This is a line of text.");}Console.WriteLine("文件寫入成功:" + filePath);}catch (Exception ex){Console.WriteLine("發生異常:" + ex.Message);}}
}
在上述示例中,我們使用StreamWriter
打開文件并使用WriteLine
方法寫入文本。同樣,通過using
語句,確保在使用完StreamWriter
后自動釋放資源。
3. 讀取二進制文件
要讀取二進制文件,可以使用BinaryReader
類。以下是一個讀取二進制文件的示例:
using System;
using System.IO;class Program
{static void Main(string[] args){string filePath = "binary.dat";try{using (BinaryReader reader = new BinaryReader(File.OpenRead(filePath))){int intValue = reader.ReadInt32();double doubleValue = reader.ReadDouble();Console.WriteLine("整數值:" + intValue);Console.WriteLine("雙精度值:" + doubleValue);}}catch (FileNotFoundException){Console.WriteLine("文件不存在:" + filePath);}catch (Exception ex){Console.WriteLine("發生異常:" + ex.Message);}}
}
在上述示例中,我們使用BinaryReader
讀取二進制文件中的整數和雙精度值。
4. 寫入二進制文件
要寫入二進制文件,可以使用BinaryWriter
類。以下是一個寫入二進制文件的示例:
using System;
using System.IO;class Program
{static void Main(string[] args){string filePath = "binary_output.dat";try{using (BinaryWriter writer = new BinaryWriter(File.OpenWrite(filePath))){int intValue = 42;double doubleValue = 3.14159;writer.Write(intValue);writer.Write(doubleValue);}Console.WriteLine("二進制文件寫入成功:" + filePath);}catch (Exception ex){Console.WriteLine("發生異常:" + ex.Message);}}
}
在上述示例中,我們使用BinaryWriter
寫入整數和雙精度值到二進制文件。
5. 文件讀寫的注意事項
-
在進行文件讀寫操作時,始終確保正確地處理異常。文件可能不存在、無法訪問或者發生其他問題,您應該能夠適當地捕獲并處理這些異常。
-
在使用
StreamReader
和StreamWriter
時,使用using
語句來自動釋放資源。這有助于防止資源泄漏。 -
對于二進制文件的讀寫,要確保按照相同的順序和格式讀寫數據。不同的數據類型可能占用不同的字節數,需要保持一致。
6. 總結
文件讀取和寫入是C#中常見的操作,用于從文件中讀取數據或將數據寫入文件。通過System.IO
命名空間中的類,您可以輕松實現文本文件和二進制文件的讀寫操作。無論是讀取文本文件、寫入文本文件,還是讀取二進制文件、寫入二進制文件,都需要注意異常處理、資源釋放以及數據格式的一致性。通過掌握文件讀寫技巧,您可以更好地處理和管理文件數據,從而提高程序的靈活性和功能。