简体   繁体   中英

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(). 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. 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.

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. If you want a console program, write a console program and forego GUI. If you want GUI, then write a first-class GUI program and leave the console window out of it.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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