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

我正在编写一个小实用程序,首先选择一个文件,然后我需要选择一个文件夹。我希望将文件夹默认设置为所选文件所在的位置。

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,等?

272874 次浏览

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

Usage is simple.

string directoryPath = Path.GetDirectoryName(filePath);
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}

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

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


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

how about this:

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

Here's the simple way to do It !

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

This was all I needed for the full path to a file

@openFileDialog1.FileName