4
votes

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.

1
try the following op.Filter = Text Files (.txt)|.txt|All Files (.)|*.*` if you need to add different types then you should probable build the filter using the string.Format function also why did you not look here first MSDN OpenFileDialog.Filter PropertyMethodMan
A console mode app is a pretty hostile place for this dialog, it requires an STA thread. You do have a bug, your Filter property assignment isn't correct. Consider op.Filter = extension1 + " files|*." + extension1;Hans Passant

1 Answers

5
votes

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