HoodedDeath
HoodedDeath

Reputation: 25

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;

Upvotes: 0

Views: 1464

Answers (2)

CodeHxr
CodeHxr

Reputation: 885

I'm fairly confident that none of the modal dialogs don't work that way. While you can say:

var foo = new OpenFileDialog().ShowDialog();

The result of that is a DialogResult, and not the filename property you're looking for. Additionally, you would no longer have a reference to the actual FileDialog object and could no longer extract the chosen filename anyway.

One alternative available to you is to make a method that makes it "look" like you're doing it with a single call:

public static string GetFilename()
{
    var dlg = new OpenFileDialog();
    var result = dlg.ShowDialog();
    var filename = dlg.FileName;

    return filename;
}

public static void Main()
{
    var userChosenFile = GetFilename();
    var aDifferentChosenFile = GetFilename();
    var yetAnotherChosenFile = GetFilename();
}

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

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.

Upvotes: 2

Related Questions