Search code examples
c#winformsopenfiledialog

Show an OpenFileDialog and get the FileName property from it in one line


I'm working on a simple application and I'm trying to get a shortcut to an exe that the user chooses. It's working as it is, but I was wondering if it's possible to open the dialog box and get the file path from it in one line so that I don't have to store the dialog box in memory.

I know it's possible to call multiple methods on one line, such as string[] array = value.Trim().ToLower().Split('\\'); but when I try to do that type of setup with the OpenFileDialog, I get an error about the methods not existing.

Here's the code I have right now:

OpenFileDialog box = new OpenFileDialog(); box.ShowDialog(); pathTextBox.Text = d.FileName;

I was wondering if it would be possible (for neatness sake) to set it up something like pathTextBox.Text = new OpenFileDialog().ShowDialog().FileName;


Solution

  • Short answer: it is called method call chaining. It works with Trim().ToLower().Split() because Trim() and ToLower() return string. You cannot chain call to ShowDialog this way, because ShowDialog method returns DialogResult which is just an enum.

    However, in theory you could extract this to a separate extension method:

    public static class OpenFileDialogExtensions
    {
        public static string ShowDialogAndReturnFileName(this OpenFileDialog dialog)
        {
            // consider checking arguments
            dialog.ShowDialog(); 
            // consider checking the result of `ShowDialog` (e.g., user could close the dialog)
            return dialog.FileName;
        }
    }
    
    // Usage, just like you want:
    pathTextBox.Text = new OpenFileDialog().ShowDialogAndReturnFileName();
    

    Keep in mind that shorter code doesn't mean better code.
    Perhaps, the best way to do this is not to do this.