WPF的檔案讀寫儲存操作示例
阿新 • • 發佈:2019-02-14
包含開啟檔案,儲存檔案,檔案讀取選擇對話方塊,檔案儲存選擇對話方塊。
1.開啟指定位置的檔案,如果檔案存在則覆蓋
public void createFile() { fileCount++; System.DateTime currentTime = new System.DateTime(); currentTime = DateTime.Now; string path = "./Test"; FileStream fs = new FileStream(path, FileMode.Create); StreamWriter sw = new StreamWriter(fs); sw.Write("//Code created by ImageGoLCD at "+currentTime); sw.Flush(); sw.Close(); fs.Close(); }
2.開啟檔案,尋找末尾並將資料新增到末尾
public void writeFile(string str) { string path = "./tempCode" + fileCount + ".txt"; FileStream fs = new FileStream(path, FileMode.Append); StreamWriter sw = new StreamWriter(fs); sw.Write(str); sw.Flush(); sw.Close(); fs.Close(); }
3.呼叫windows的檔案開啟對話方塊開啟圖片檔案
var openFileDialog = new Microsoft.Win32.OpenFileDialog() { Filter = "*.jpg,*.jpeg,*.bmp,*.jif,*.ico,*.png,*.tif,*.wmf|*.jpg;*.jpeg;*.bmp;*.gif;*.ico;*.png;*.tif;*.wmf" }; var result = openFileDialog.ShowDialog(); if (result == true) { path = openFileDialog.FileName;//傳入選擇的檔案路徑到path中 }
4.呼叫windows的檔案儲存對話方塊儲存txt格式檔案,如果檔案存在覆蓋這個檔案
var saveFileDialog = new Microsoft.Win32.SaveFileDialog();
saveFileDialog.Filter = "TXT File(*.txt)|*.txt";
var result = saveFileDialog.ShowDialog();
if (result == true)
{
FileStream savefs = new FileStream(saveFileDialog.FileName, FileMode.Create);
StreamWriter savesw = new StreamWriter(savefs);
savesw.Flush();
savesw.Close();
}