
encryptgui.cs 完整的範例程式碼,請參考encryptgui.cs
如果某次編碼結果不錯,我們往後想要繼續利用同一個 Encrypt 物件,這時候就需要把 Encrypt 物件儲存下來。想一想我們存檔應該儲存什麼?把整個 Encrypt 物件都儲存下來,還是只要儲存編碼用的 cArray 就可以了呢?
簡單一點,就儲存 cArray 到文字檔就可以了,然後載入後也可以直接用 Encrypt 的 Code 屬性設定。儲存檔案要用到 System.IO 的名稱空間 (namespace) ,因此要先 using 進來
using System.IO;
然後利用 saveButton_Click() 進行存檔工作
this.saveButton.Click += new EventHandler(this.saveButton_Click);
saveButton_Click() 如下
private void saveButton_Click(object sender, EventArgs e) {
string path = @"data.txt";
try {
File.WriteAllText(path, this.e.Code);
this.displayLabel.Text = "This is Save button. Encrypt object is saved.";
}
catch (NullReferenceException nre) {
this.displayLabel.Text = "This is Save button. There is no Encrypt Object.";
}
}預設檔名為 data.txt ,這裡用的是不會處理跳脫字元的 @ 前綴字串。存檔工作也很簡單,利用 File.WriteAllText() 即可把字串寫進檔案之中
try {
File.WriteAllText(path, this.e.Code);
this.displayLabel.Text = "This is Save button. Encrypt object is saved.";
}
catch (NullReferenceException nre) {
this.displayLabel.Text = "This is Save button. There is no Encrypt Object.";
}留意這裡仍有屬性 e 未建立的風險,因此也要進行例外處理 (exception handling) 。 File.WriteAllText() 會依指定路徑存入字串到檔案內,若路徑中的檔案不存在,就會建立新的檔案,由於此處的路徑直接指定檔名,因此會儲存 Code 到相同路徑下(相同資料夾中)。
載入由 loadButton_Click() 進行
this.loadButton.Click += new EventHandler(this.loadButton_Click);
loadButton_Click() 如下
private void loadButton_Click(object sender, EventArgs e) {
string path = @"data.txt";
if (File.Exists(path)) {
try {
string code = File.ReadAllText(path, Encoding.UTF8);
this.e.Code = code;
this.displayLabel.Text = "This is Load button. Encrypt object is loaded.";
}
catch (NullReferenceException nre) {
this.displayLabel.Text = "This is Load button. Encrypt object is not loaded.";
}
}
else {
this.displayLabel.Text = "This is Load button. There is no file.";
}
}雖然寫檔可以直接寫入,讀檔沒有檔案的話卻是個麻煩,因此這裡先以 File.Exists() 先判斷檔案是否存在
if (File.Exists(path)) {讀檔利用 File.ReadAllText() ,第二個參數 (parameter) 為檔案編碼,這裡用 Encoding.UTF8 ,也就是 UTF-8 的編碼格式
try {
string code = File.ReadAllText(path, Encoding.UTF8);
this.e.Code = code;
this.displayLabel.Text = "This is Load button. Encrypt object is loaded.";
}
catch (NullReferenceException nre) {
this.displayLabel.Text = "This is Load button. Encrypt object is not loaded.";
}編譯後執行,存檔成功

開啟文字檔,內容就是 Code 字串

載入也沒問題

存檔與載入的功能完成了,接下來,我們建置 Clear 與 Copy 兩個按鈕,使之成為完成版的 GUI 軟體。
| 中英文術語對照 | |
|---|---|
| 物件 | object |
| 屬性 | property |
| 方法 | method |
| 名稱空間 | namespace |
| 例外處理 | exception handling |
| 參數 | parameter |
您可以繼續參考
GUI 篇
相關目錄
回 C# 入門指南
回 C# 教材
回首頁
參考資料
http://msdn.microsoft.com/zh-tw/library/system.io.file%28v=vs.80%29.aspx
http://msdn.microsoft.com/zh-tw/library/8bh11f1k.aspx
http://msdn.microsoft.com/zh-tw/library/ezwyzy7b.aspx
沒有留言:
張貼留言