问题描述
我创建了一个软件,可以在 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.Windows
、using Microsoft.Win32;
和 using System.IO;
。
您还必须将 WindowsAPICodePack
库添加到您的项目中才能使用文件夹选择器。您可以使用 NuGet 管理器执行此操作。这是图书馆的链接:WindowsAPICodePack - 1.1.1