C# 从 OpenFileDialog 路径/文件名中提取路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/439007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:26:04  来源:igfitidea点击:

Extracting Path from OpenFileDialog path/filename

c#.netparsingpath

提问by Kevin Haines

I'm writing a little utility that starts with selecting a file, and then I need to select a folder. I'd like to default the folder to where the selected file was.

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

OpenFileDialog.FileNamereturns the full path & filename- what I want is to obtain just the path portion (sans filename), so I can use that as the initial selected folder.

OpenFileDialog.FileName返回完整路径和文件名- 我想要的是仅获取路径部分 (sans 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)
    {
       ...
    }

Are there any .NET methods to do this, or do I need to use regex, split, trim,etc??

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

采纳答案by Jeff Yates

Use the Pathclass from System.IO. It contains useful calls for manipulating file paths, including GetDirectoryNamewhich does what you want, returning the directory portion of the file path.

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

Usage is simple.

用法很简单。

string directoryPath = Path.GetDirectoryName(filePath);

回答by Max

if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
    strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}

回答by Shaahin

You can use FolderBrowserDialog instead of FileDialog and get the path from the OK result.

您可以使用 FolderBrowserDialog 而不是 FileDialog 并从 OK 结果中获取路径。

FolderBrowserDialog browser = new FolderBrowserDialog();
string tempPath ="";

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

回答by Jan Machá?ek

how about this:

这个怎么样:

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

回答by Abdel

Here's the simple way to do It !

这是做到这一点的简单方法!

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