包含打开文件,保存文件,文件读取选择对话框,文件保存选择对话框。
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();
}