文件的打开与保存以及文件夹的打开都是文件的基本操作,实现起来比较简单,打开文件使用OpenFileDialog类,保存文件用SaveFileDialog类,打开文件夹用FolderBrowserDialog类。下面分别介绍这三种情况的示例代码:
1、打开文件
OpenFileDialog pOpenFileDialog = new OpenFileDialog();
pOpenFileDialog.Filter = "所有文件|*.*";//若打开指定类型的文件只需修改Filter,如打开txt文件,改为*.txt即可
pOpenFileDialog.Multiselect = false;
pOpenFileDialog.Title = "打开文件";
if (pOpenFileDialog.ShowDialog() == DialogResult.OK)
{
string path = pOpenFileDialog.FileName;
}
2、保存文件
SaveFileDialog pSaveFileDialog = new SaveFileDialog
{
Title = "保存为:",
RestoreDirectory = true,
Filter = "所有文件(*.*)|*.*"
};//同打开文件,也可指定任意类型的文件
if (pSaveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = pSaveFileDialog.FileName;
}
3、打开文件夹
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择文件夹路径";
if (dialog.ShowDialog() == DialogResult.OK)
{
string path = dialog.SelectedPath;
}