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

Adr*_*ian 4 c# openfiledialog

我正在使用控制台应用程序测试一个类,并且在该类中要求用户选择一个文件。我创建一个 OpenFileDialog 类实例,设置过滤器,激活多选并调用 ShowDialog()。我选择一个文件,它返回 true,但 FileName 字段中有一个空字符串,FileNames 中有 0 个项目 string[]。我缺少什么?

这是代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

扩展名永远不会为空,我已经尝试过几个文件扩展名。根据记录,我在 Win32 之前使用了 Forms 类,并且运行良好。

Pet*_*iho 5

我同意这样的评论:至少可以说,在控制台应用程序中使用对话框窗口不太理想。即使在 Visual Studio 工具中,显示窗口的命令行工具也有历史先例,但在这些情况下,这是一个非常有限的场景:命令行帮助的 GUI 版本。如果您想要控制台程序,请编写控制台程序并放弃 GUI。如果你想要 GUI,那么就编写一个一流的 GUI 程序并将控制台窗口排除在外。

也就是说,在我看来,您的问题与程序的控制台性质没有任何关系。相反,这只是您没有提供文件类型过滤器的描述。我不清楚为什么这会改变对话框的行为,但确实如此。改成这样:

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;
}
Run Code Online (Sandbox Code Playgroud)