Form.ShowDialog 方法

问题描述

我创建了一个软件,可以在 Excel 文件中保存一些信息。该软件有两种可能性:

  1. 选择文件夹,然后软件会创建一个随机名称的Excel文件并保存数据,或者

  2. 选择一个现有的由用户创建的 Excel 文件并保存数据。

如何创建一个 ONE ShowDialog 来询问用户您要选择文件夹还是文件?!

我用来选择文件夹的代码

using (var fbd = new FolderbrowserDialog())
           {
               DialogResult result = fbd.ShowDialog();

               if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.Selectedpath))
               {

                   textBox3.Text = fbd.Selectedpath;

               }
          }

我用来选择文件代码

OpenFileDialog excelFilename = new OpenFileDialog();

           if (excelFilename.ShowDialog() == DialogResult.OK)
           {
               textBox3.Text = excelFilename.FileName;

           }

解决方法

也许是这样的?:

MessageBoxResult result = MessageBox.Show("Ask user what he wants to do","",MessageBoxButton.YesNo);

string path = null;

//MessageBoxResult.Yes means File,.No means Folder
if (result == MessageBoxResult.Yes)
{
    //File-Picker
    OpenFileDialog filePicker = new OpenFileDialog()
    {
        FileName = "Excel File",DefaultExt = ".xls",Filter = "Excel Document | *.xls"
    };

    if (filePicker.ShowDialog() == true) 
    {
        path = filePicker.FileName;
    }
}
else if (result == MessageBoxResult.No)
{
    //Folder-Picker
    CommonOpenFileDialog folderPicker = new CommonOpenFileDialog()
    {
        IsFolderPicker = true,Multiselect = false
    };

    path = Path.Combine(folderPicker.FileName,DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"));
    
    //Create file in folder
    File.Create(path);
}

if (path != null)
{
    // Do something with path (file user selected/program created)
}

确保您在程序开始时使用了 using System.Windowsusing Microsoft.Win32;using System.IO;

您还必须将 WindowsAPICodePack 库添加到您的项目中才能使用文件夹选择器。您可以使用 NuGet 管理器执行此操作。这是图书馆的链接:WindowsAPICodePack - 1.1.1