显示一个 OpenFileDialog 并在一行中从中获取文件名 属性

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

我正在开发一个简单的应用程序,我正在尝试获取用户选择的 exe 的快捷方式。它按原样工作,但我想知道是否可以打开对话框并在一行中从中获取文件路径,这样我就不必将对话框存储在内存中。

我知道可以在一行中调用多个方法,例如 string[] array = value.Trim().ToLower().Split('\'); 但是当我尝试使用 OpenFileDialog 进行此类设置时,我收到有关方法不存在的错误。

这是我现在拥有的代码:

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

我想知道是否可以(为了整洁起见)将其设置为 pathTextBox.Text = new OpenFileDialog().ShowDialog().FileName;

简答:它被称为方法调用链接。它适用于 Trim().ToLower().Split(),因为 Trim()ToLower() return string。您不能以这种方式链接调用 ShowDialog,因为 ShowDialog 方法 returns DialogResult 只是一个 enum

但是,理论上您可以将其提取到单独的扩展方法中:

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

请记住,更短的代码并不意味着更好的代码
也许,做到这一点的最好方法就是不这样做。

我相当确信 none 的模态对话框不是那样工作的。当你可以说:

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

结果是DialogResult,而不是您要查找的文件名 属性。此外,您将不再拥有对实际 FileDialog 对象的引用,并且无法再提取所选文件名。

您可以使用的一种替代方法是制作一种方法,使其 "look" 就像您通过一次调用所做的那样:

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