[C#] 檔案讀寫
檔案讀寫是程式設計師很常遇到的問題,在 C# 中與 Java 相同,不管是檔案讀寫、網路資料傳送、螢幕鍵盤輸出入都是以「串流(Stream)」的方式來達成。FileStream、MemoryStream、NetworkStream、GZipStream 等都繼承自 Stream 類別。在這個章節裡我們直接以範例來學習。
一、文字讀寫
1. 將文字寫入 C:\secret_plan.txt 中。
| 2 | StreamWriter sw = newStreamWriter(@"C:\secret_plan.txt"); | 
 
| 3 | sw.WriteLine("write something");             | 
 
 
 
2. 讀取文字
| 2 | StreamReader sr = newStreamReader(@"C:\secret_plan.txt"); | 
 
| 3 | while(!sr.EndOfStream) {                | 
 
| 4 |     stringline = sr.ReadLine();             | 
 
 
 
Stream 類別實作了 IDisposable 介面!它具有 Dispose 方法,你可以呼叫 Dispose 關閉串流或者使用 using statement。
| 1 | using(StreamWriter sw = newStreamWriter(@"C:\secret_plan.txt")) { | 
 
 
 
  看到這裡是不是覺得太簡單了呢!等等呢,Visual C# 有一個 OpenFileDialog 的對話框可以用來選取檔案。下面就來看看怎麼使用吧!
Step1:將 OpenFileDialog 控制項拖曳到表單上
拖曳新增後 OpenFileDialog 控制項會出現在 Form Design 下方。在此我們假定該控制項命名 openFileDialog1 。
Step2:撰寫控制碼
在 Form 底下撰寫 OpenFileDialog 的控制碼。
| 1 | openFileDialog1.InitialDirectory = @"c:\MyFolder\Default\";  | 
 
| 3 | openFileDialog1.Filter = "Text Files (*.txt)|*.txt|Comma-Delimited Files (*.csv)|*.csv|All Files (*.*)|*.*"; | 
 
| 4 | openFIleDialog1.CheckFileExists = true;              | 
 
| 5 | openFIleDialog1.CheckPathExists = false; | 
 
| 6 | DialogResult result = openFileDialog1.ShowDialog();      | 
 
| 7 | if(result == DialogResult.OK) { | 
 
 
 
除了 OpenFileDialog 外,SaveFileDialog 的作法也是一樣的。
二、File 類別 - 更快的方法來處理簡單的檔案管理
| 1 | boolb = File.Exists(file_name);         | 
 
| 3 | stringtext = File.ReadAllText(file_name);   | 
 
| 4 | File.WriteAllText(file_name, text);      | 
 
 
 
* File 類別還有很多方法,詳細參考 Head First C#、其他書籍或 MSDN
三、物件序列化(serialization)
  物件序列化是一個快速又方便的物件狀態永久保存法,它將物件的狀態(所有成員變數)儲存到檔案中。以下範例展示序列化(serialize)與反序列化(deserialize)。
| 5 |     publicAnotherObj another;   | 
 
 
 
Step1:引入 namespace
在 .cs 檔前頭加上 using System.Runtime.Serialization.Formatters.Binary;
Step2:建立序列化的串流
| 1 | BinaryFormatter formatter = newBinaryFormatter(); | 
 
 
 
Step3:開始序列化(serialize)
| 1 | Stream output = File.Create(file_name); | 
 
| 2 | formatter.Serialize(output, objectToSerialize); | 
 
 
 
Step4:反序列化(deserialize)
| 1 | Stream input = File.OpenRead(file_name); | 
 
| 2 | SomeObj obj = (SomeObj)formatter.Deserialize(input); | 
 
 
 
四、二進制檔案讀寫
  除了文字檔,我們也可能保存 int、float 等變數的數值或是 byte 資料,這時候使用二進制檔案(binary)就比較方便了。
| 2 | using(FileStream output = File.Create("binarydata.dat")) {          | 
 
| 3 |     BinaryWriter writer = newBinaryWriter(output); | 
 
| 6 | using(FileStream input = newFileStream(@"binarydata.dat", FileMode.Open)) {    | 
 
| 7 |     BinaryReader reader = newBinaryReader(input); | 
 
| 8 |     intdata = reader.ReadInt16(); | 
 
 
 
  以上只針對最簡單的檔案讀寫來說明,其實不僅是檔案,包括網路串流、壓縮串流都是以類似的作法做輸出入,如欲深入瞭解請參閱其他書籍或 MSDN。                          by autosun
 
 
沒有留言:
張貼留言