【问题标题】:C# FilePath HelpC# 文件路径帮助
【发布时间】:2011-02-09 15:06:21
【问题描述】:

我使用 OpenFileDialog 来搜索特定文件。当用户选择文件时,我想将该路径存储在变量中。但是,这些似乎不是 OpenFileDialog 中的选项?

有人知道怎么做吗?

谢谢。

编辑:这是 Winforms,我不想保存包含文件名的路径,只保存文件所在的位置。

【问题讨论】:

    标签: c# winforms openfiledialog


    【解决方案1】:

    如果您使用的是 WinForms,请使用您的 OpenFileDialog 实例的 FileName 属性。

    【讨论】:

    • 该属性在 SL 中不存在,仅供参考;不确定 OP 正在使用什么...
    • 最后是 String path = System.IO.Path.GetDirectoryName(FileName);
    【解决方案2】:

    在 WinForms 上:

    String fileName;
    OpenFileDialog ofd = new OpenFileDialog();
    DialogResult dr = ofd.ShowDialog();
    if (dr == DialogResult.Ok) {
      fileName = ofd.FileName;
    }
    
    //getting only the path:
    String path = fileName.Substring(0, fileName.LastIndexOf('\\'));
    
    //or easier (thanks to Aaron)
    String path = System.IO.Path.GetDirectoryName(fileName);
    

    【讨论】:

    • 这包括我不想要的文件名。只是文件所在的路径。我应该更清楚一点。
    • 不需要子串;字符串路径 = System.IO.Path.GetDirectoryName(fileName);
    【解决方案3】:

    这将根据OpenFileDialogFileName 属性检索您的路径。

    String path = System.IO.Path.GetDirectoryName(OpenFileDialog.FileName);
    

    【讨论】:

      【解决方案4】:

      我不会从 MSDN 复制粘贴答案,而是直接链接到它们。

      Forms OpenFileDialog 上的 MSDN 文档。

      WPF OpenFileDialog 上的 MSDN 文档。

      请在发布问题之前尝试寻找答案。

      【讨论】:

        【解决方案5】:

        您将路径存储在其他地方!

        我通常做的是创建一个用户范围的配置变量。

        以下是它的使用示例:

        var filename = Properties.Settings.Default.LastDocument;
        var sfd = new Microsoft.Win32.SaveFileDialog();
        sfd.FileName = filename;
        /* configure SFD */
        var result = sfd.ShowDialog() ?? false;
        if (!result)
            return;
        /* save stuff here */
        Properties.Settings.Default.LastDocument = filename;
        Properties.Settings.Default.Save();
        

        要仅保存目录,请使用System.IO.Path.GetDirectoryName()

        【讨论】:

        • 谢谢,您的最终建议为我指明了正确的方向。我使用 System.IO.Directory.GetParent(openFileDialog1.FileName).ToString();这非常有效。谢谢。
        【解决方案6】:

        对话框关闭后,OpenFileDialog 对象上应该有一个文件路径(或类似的东西)属性,它将存储用户输入的任何文件路径。

        【讨论】:

          【解决方案7】:

          试试文件名。如果您允许选择多个文件,则为 FileNames(Multiselect=true)

          【讨论】: