我一直在尝试遵循教程和各种Stack Overflow帖子等,以实现OpenFileDialog来选择文件。问题是,看来我无法让我的程序继续其余的逻辑。不能完全确定它是否与我要在主窗口中打开文件对话框有关。请考虑以下代码段:
public MainWindow()
{
InitializeComponent();
string file = "";
// Displays an OpenFileDialog so the user can select a file.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Files|*.txt;*.out";
openFileDialog1.Title = "Select a File";
openFileDialog1.ShowHelp = true;
// Show the Dialog.
// If the user clicked OK in the dialog and
// a file was selected, open it.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//file = openFileDialog1.FileName;
//file = openFileDialog1.OpenFile().ToString();
//openFileDialog1.Dispose();
}
openFileDialog1 = null;
Console.WriteLine("File path is: " + file);
如您所见,我什至尝试在对话框结束之前将“帮助”值设置为true。我试图同时选择文件字符串的文件名等,但无济于事-该程序似乎只是在从对话框中选择文件后等待。这里有人可以提出解决方案的建议吗?
答案 0 :(得分:1)
OpenFileDialog.ShowDialog()
是modal method:
FileDialog是模式对话框。因此,如图所示,它会阻止 其余的应用程序,直到用户选择了文件。当一个 对话框以模态显示,无输入(键盘或鼠标单击) 除了对话框上的对象以外,都可能发生。该程序必须隐藏 或关闭对话框(通常是为了响应某些用户操作) 才能输入到调用程序。
这意味着调用此方法将阻塞您的主线程,直到关闭对话框。您可以选择的一些选项是:
答案 1 :(得分:1)
以前,我在WPF上也遇到同样的问题。使用WPF时,System.Windows.Form
中不包含Project references
命名空间;
,实际上,有两个OpenFileDialog,第一个是System.Windows.Forms.OpenFileDialog
(这是您拥有的),第二个是Microsoft.Win32.OpenFileDialog
。如果要使代码正常工作,必须在引用中添加System.Windows.Forms
:
解决方案资源管理器-> YourProject
->引用(右键单击并添加引用...)->组装->框架->查找并选择System.Windows.Forms
->确定
,下一个解决方案是使用Microsoft.Win32
,这很容易。只需将此命名空间添加到您的代码文件中,然后像这样更改您的代码:
string file = "";
// Displays an OpenFileDialog so the user can select a file.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Files|*.txt;*.out";
openFileDialog1.Title = "Select a File";
// Show the Dialog.
// If the user clicked OK in the dialog and
// a file was selected, open it.
if (openFileDialog1.ShowDialog() == true)
{
file = openFileDialog1.FileName;
//file = openFileDialog1.OpenFile().ToString();
//openFileDialog1.Dispose();
}
openFileDialog1 = null;
Console.WriteLine("File path is: " + file);