對這文章發表回應
發表限制: 非會員 可以發表
2010 04 01 22 06 [C#] 檔案讀寫
From: Head First C# [Chapter 9] Reading and writing files
檔案讀寫是程式設計師很常遇到的問題,在 C# 中與 Java 相同,不管是檔案讀寫、網路資料傳送、螢幕鍵盤輸出入都是以「串流(Stream)」的方式來達成。FileStream、MemoryStream、NetworkStream、GZipStream 等都繼承自 Stream 類別。在這個章節裡我們直接以範例來學習。
一、文字讀寫
1. 將文字寫入 C:\secret_plan.txt 中。
// 建立檔案串流(@ 可取消跳脫字元 escape sequence)
StreamWriter sw = new StreamWriter(@"C:\secret_plan.txt");
sw.WriteLine("write something"); // 寫入文字
sw.Close(); // 關閉串流
2. 讀取文字
// 建立檔案串流(@ 可取消跳脫字元 escape sequence)
StreamReader sr = new StreamReader(@"C:\secret_plan.txt");
while (!sr.EndOfStream) { // 每次讀取一行,直到檔尾
string line = sr.ReadLine(); // 讀取文字到 line 變數
}
sr.Close(); // 關閉串流
Stream 類別實作了 IDisposable 介面!它具有 Dispose 方法,你可以呼叫 Dispose 關閉串流或者使用 using statement。using (StreamWriter sw = new StreamWriter(@"C:\secret_plan.txt")) {
...
}
看到這裡是不是覺得太簡單了呢!等等呢,Visual C# 有一個 OpenFileDialog 的對話框可以用來選取檔案。下面就來看看怎麼使用吧!
Step1:將 OpenFileDialog 控制項拖曳到表單上
拖曳新增後 OpenFileDialog 控制項會出現在 Form Design 下方。在此我們假定該控制項命名 openFileDialog1 。
Step2:撰寫控制碼
在 Form 底下撰寫 OpenFileDialog 的控制碼。
openFileDialog1.InitialDirectory = @"c:\MyFolder\Default\"; // 檔案對話方框開啟的預設資料夾
// 設定可以選擇的檔案類型
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|Comma-Delimited Files (*.csv)|*.csv|All Files (*.*)|*.*";
openFIleDialog1.CheckFileExists = true; // 若檔案/路徑 不存在是否顯示錯誤訊息
openFIleDialog1.CheckPathExists = false;
DialogResult result = openFileDialog1.ShowDialog(); // 顯示檔案對話方框並回傳狀態(DialogResult.OK、DialogResult.Cancel)
if (result == DialogResult.OK) {
// 操作檔案 openFileDialog1.FileName
}除了 OpenFileDialog 外,SaveFileDialog 的作法也是一樣的。
二、File 類別 - 更快的方法來處理簡單的檔案管理
bool b = File.Exists(file_name); // 判定檔案是否存在
File.Create(file_name); // 建立檔案
string text = File.ReadAllText(file_name); // 讀取檔案內所有文字
File.WriteAllText(file_name, text); // 將 text 寫入檔案
* File 類別還有很多方法,詳細參考 Head First C#、其他書籍或 MSDN
三、物件序列化(serialization)
物件序列化是一個快速又方便的物件狀態永久保存法,它將物件的狀態(所有成員變數)儲存到檔案中。以下範例展示序列化(serialize)與反序列化(deserialize)。
[Serializable] // *這一行很重要
class AnotherObj {}
class SomeObj {
public int x; // 該變數會被保存
public AnotherObj another; // 該物件也會被保存,但其類別需加上 [Serializable] 屬性(attribute)
}
Step1:引入 namespace
在 .cs 檔前頭加上 using System.Runtime.Serialization.Formatters.Binary;
Step2:建立序列化的串流
BinaryFormatter formatter = new BinaryFormatter();
Step3:開始序列化(serialize)
Stream output = File.Create(file_name);
formatter.Serialize(output, objectToSerialize);
output.Close();
Step4:反序列化(deserialize)
Stream input = File.OpenRead(file_name);
SomeObj obj = (SomeObj)formatter.Deserialize(input);
input.Close();
四、二進制檔案讀寫
除了文字檔,我們也可能保存 int、float 等變數的數值或是 byte 資料,這時候使用二進制檔案(binary)就比較方便了。
int value = 43;
using (FileStream output = File.Create("binarydata.dat")) { // 寫入整數值
BinaryWriter writer = new BinaryWriter(output);
writer.Write(value);
}
using (FileStream input = new FileStream(@"binarydata.dat", FileMode.Open)) { // 讀取整數值
BinaryReader reader = new BinaryReader(input);
int data = reader.ReadInt16();
}
以上只針對最簡單的檔案讀寫來說明,其實不僅是檔案,包括網路串流、壓縮串流都是以類似的作法做輸出入,如欲深入瞭解請參閱其他書籍或 MSDN。
by autosun
原文出處:[C#] 檔案讀寫 @ 奧托森學習手札 :: 隨意窩 Xuite日誌