C# winform 窗体弹出选择目录或文件 的对话框

C# winform 窗体弹出选择目录或文件 的对话框

//弹出一个选择目录的对话框

privatevoid btnSelectPath_Click(object sender, EventArgs e) //弹出一个选择目录的对话框
 {
    FolderBrowserDialog path = new FolderBrowserDialog();
    path.ShowDialog();
this.txtPath.Text = path.SelectedPath;
 }

//弹出一个选择文件的对话框

privatevoid btnSelectFile_Click(object sender, EventArgs e) //弹出一个选择文件的对话框
 {
    OpenFileDialog file = new OpenFileDialog();
    file.ShowDialog();
this.txtFile.Text = file.SafeFileName;
 }

c#获取要保存文件的对话框,用SaveFileDialog类。具体用法很简单分享一下吧,对于初学者可能有用

 string localFilePath = "", fileNameExt = "", newFileName = "", FilePath = "";
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            //设置文件类型
            //书写规则例如:txt files(*.txt)|*.txt
            saveFileDialog.Filter = "txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|All files(*.*)|*.*";
            //设置默认文件名(可以不设置)
            saveFileDialog.FileName = "siling-Data";
            //主设置默认文件extension(可以不设置)
            saveFileDialog.DefaultExt = "xml";
            //获取或设置一个值,该值指示如果用户省略扩展名,文件对话框是否自动在文件名中添加扩展名。(可以不设置)
            saveFileDialog.AddExtension = true;
            //设置默认文件类型显示顺序(可以不设置)
            saveFileDialog.FilterIndex = 2;

            //保存对话框是否记忆上次打开的目录
            saveFileDialog.RestoreDirectory = true;

            // Show save file dialog box
            DialogResult result = saveFileDialog.ShowDialog();
            //点了保存按钮进入
            if (result == DialogResult.OK)
            {
                //获得文件路径
                localFilePath = saveFileDialog.FileName.ToString();
                //获取文件名,不带路径
                fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\") + 1);
                //获取文件路径,不带文件名
                FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\"));
                //给文件名前加上时间
                //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
                //在文件名里加字符
                //saveFileDialog.FileName.Insert(1,"dameng");
                //为用户使用 SaveFileDialog 选定的文件名创建读/写文件流。
                System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog.OpenFile();//输出文件
                //fs可以用于其他要写入的操作
            }

 

//弹出一个选择目录的对话框

privatevoid btnSelectPath_Click(object sender, EventArgs e) //弹出一个选择目录的对话框
 {
    FolderBrowserDialog path = new FolderBrowserDialog();
    path.ShowDialog();
this.txtPath.Text = path.SelectedPath;
 }

//弹出一个选择文件的对话框

privatevoid btnSelectFile_Click(object sender, EventArgs e) //弹出一个选择文件的对话框
 {
    OpenFileDialog file = new OpenFileDialog();
    file.ShowDialog();
this.txtFile.Text = file.SafeFileName;
 }