从OpenFileDialogpath/文件名提取path

我正在写一个实用工具,从select文件开始,然后我需要select一个文件夹。 我想默认文件夹到所选文件的位置。

OpenFileDialog.FileName返回完整的path和文件名 – 我想要的只是获得path部分(sans文件名),所以我可以使用它作为初始选定的文件夹

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方法来做到这一点,或者我需要使用正则expression式,拆分,修剪等?

使用System.IOPath类。 它包含有用的调用文件path的调用,包括GetDirectoryName ,它可以做你想做的,返回文件path的目录部分。

用法很简单。

 string directoryPath = Path.GetDirectoryName(filePath); 

这个怎么样:

 string fullPath = ofd.FileName; string fileName = ofd.SafeFileName; string path = fullPath.Replace(fileName, ""); 
 if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName; } 

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

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

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

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