【问题标题】:Extracting Path from OpenFileDialog path/filename从 OpenFileDialog 路径/文件名中提取路径
【发布时间】:2010-10-01 03:22:24
【问题描述】:

我正在编写一个从选择文件开始的小实用程序,然后我需要选择一个文件夹。我想将文件夹默认为所选文件所在的位置。

OpenFileDialog.FileName 返回 完整路径和文件名 - 我想要的只是获取 路径部分(无文件名),所以我可以使用它作为初始所选文件夹

    private System.Windows.Forms.OpenFileDialog ofd;
    private System.Windows.Forms.FolderBrowserDialog fbd;
    ...
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        string sourceFile = ofd.FileName;
        string sourceFolder = ???;
    }
    ...
    fbd.SelectedPath = sourceFolder; // set initial fbd.ShowDialog() folder
    if (fbd.ShowDialog() == DialogResult.OK)
    {
       ...
    }

是否有任何 .NET 方法可以做到这一点,还是我需要使用 regex, split, trim, 等??

【问题讨论】:

    标签: c# .net parsing path


    【解决方案1】:

    使用来自System.IOPath 类。它包含用于操作文件路径的有用调用,包括 GetDirectoryName,它执行您想要的操作,返回文件路径的目录部分。

    使用简单。

    string directoryPath = Path.GetDirectoryName(filePath);
    

    【讨论】:

    • 谢谢 - 它必须是一个简单的答案。自我提醒:不建议在午夜后编码。不仅阅读方法原型也有帮助,因为 VS 文档将其列为公共静态字符串 GetDirectoryName(string path) 并且我误解了参数。
    【解决方案2】:
    if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
    {
        strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
    }
    

    【讨论】:

    • 用户选择文件时初始目录是否改变?如果不是,那么当用户更改目录时,这种方法会导致问题。另外,我认为他不希望将FileName 作为sourceFolder 的一部分。
    【解决方案3】:

    您可以使用 FolderBrowserDialog 代替 FileDialog 并从 OK 结果中获取路径。

    FolderBrowserDialog browser = new FolderBrowserDialog();
    string tempPath ="";
    
    if (browser.ShowDialog() == DialogResult.OK)
    {
      tempPath  = browser.SelectedPath; // prints path
    }
    

    【讨论】:

    • 所以先选择文件,然后再次导航到它并选择文件夹??
    【解决方案4】:

    这个怎么样:

    string fullPath = ofd.FileName;
    string fileName = ofd.SafeFileName;
    string path = fullPath.Replace(fileName, "");
    

    【讨论】:

      【解决方案5】:

      这是简单的方法!

      string fullPath =openFileDialog1.FileName;
      string directory;
      directory = fullPath.Substring(0, fullPath.LastIndexOf('\\'));
      

      【讨论】:

        【解决方案6】:

        这就是我需要的文件完整路径

        @openFileDialog1.FileName
        

        【讨论】:

          猜你喜欢
          • 2016-06-19
          • 1970-01-01
          • 2011-11-16
          • 2012-10-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多