问题描述
我正在写一个小工具,以选择一个文件开始,然后我需要选择一个文件夹。我想默认的文件夹选定的文件在何处
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.FileName返回的完整路径和放大器;文件名 - 我想要的是获得人的路部分(没有文件名),这样我就可以使用它作为初始选择的文件夹
OpenFileDialog.FileName returns 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
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方法要做到这一点,或者我需要使用正则表达式,拆分,修剪等??
Are there any .NET methods to do this, or do I need to use regex, split, trim, etc??
推荐答案
使用的从的。它包含了操作文件路径,包括这你想要做什么,返回文件路径的目录部分。
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.
用法很简单。
string directoryPath = Path.GetDirectoryName(filePath);
这篇关于从打开文件对话框路径/文件名路径提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!