简体   繁体   English

Microsoft.Win32中的OpenFileDialog.FileName返回空字符串

[英]OpenFileDialog.FileName from Microsoft.Win32 returning empty strings

I am testing a class with a console application and in the class the user is asked to select a file. 我正在测试一个带有控制台应用程序的类,并且在类中要求用户选择一个文件。 I create a OpenFileDialog class instance, set the filters, activate multiselect and call ShowDialog(). 我创建一个OpenFileDialog类实例,设置过滤器,激活multiselect并调用ShowDialog()。 I select a file/s and it returns true but there's an empty string on the field FileName an a 0 items string[] in FileNames. 我选择一个文件/ s并返回true但是FileName字段中有一个空字符串,FileNames中有一个0项字符串[]。 What am I missing? 我错过了什么?

Here is the code: 这是代码:

private static string[] OpenFileSelector(string extension1)
{
    OpenFileDialog op = new OpenFileDialog();
    op.InitialDirectory = @"C:\";
    op.Title = "Seleccione los archivos";
    op.Filter = "|*." + extension1;
    op.Multiselect = true;

    bool? res = op.ShowDialog();

    if (res != null && res.Value) return op.FileNames;
    return null;
}

Extension is never empty and I've tried with several file extensions. 扩展永远不会是空的,我尝试过几个文件扩展名。 For the record, I used the Forms class before the Win32 and it worked fine. 为了记录,我在Win32之前使用了Forms类,它工作正常。

I agree with the comments that the use of a dialog window in a console application is less than ideal, to say the least. 我同意评论说,在控制台应用程序中使用对话框窗口并不理想,至少可以这么说。 There is historical precedent, even in the Visual Studio tools, for command line tools that display a window, but in these cases it's a very limited scenario: a GUI version of the command-line help. 对于显示窗口的命令行工具,即使在Visual Studio工具中也有历史先例,但在这些情况下,这是一个非常有限的场景:命令行帮助的GUI版本。 If you want a console program, write a console program and forego GUI. 如果你想要一个控制台程序,编写一个控制台程序并放弃GUI。 If you want GUI, then write a first-class GUI program and leave the console window out of it. 如果您想要GUI,那么编写一流的GUI程序并将控制台窗口从中删除。

That said, it does not appear to me that your problem has anything to do with the console nature of your program. 也就是说,在我看来,您的问题与程序的控制台性质无关。 Instead, it's simply that you are not providing a description for your file type filter. 相反,它只是您没有提供文件类型过滤器的描述。 It's not clear to me why this should change the behavior of the dialog, but it does. 我不清楚为什么这会改变对话框的行为,但确实如此。 Change to something like this: 换成这样的东西:

private static string[] OpenFileSelector(string description, string extension1)
{
    if (string.IsNullOrEmpty(description))
    {
        throw new ArgumentException("description must be a non-empty string");
    }

    OpenFileDialog op = new OpenFileDialog();
    op.InitialDirectory = @"C:\";
    op.Title = "Seleccione los archivos";
    op.Filter = description + "|*." + extension1;
    op.Multiselect = true;

    bool? res = op.ShowDialog();

    if (res != null && res.Value) return op.FileNames;
    return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM