[英]Extracting Path from OpenFileDialog path/filename
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
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 . 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)
{
...
}
Are there any .NET methods to do this, or do I need to use regex, split, trim,
etc??是否有任何 .NET 方法可以做到这一点,或者我是否需要使用
regex, split, trim,
等??
Use the Path
class from System.IO
. 使用
System.IO
的Path
类。 It contains useful calls for manipulating file paths, including GetDirectoryName
which does what you want, returning the directory portion of the file path. 它包含用于操作文件路径的有用调用,包括
GetDirectoryName
,它可以执行您想要的操作,返回文件路径的目录部分。
Usage is simple. 用法很简单。
string directoryPath = Path.GetDirectoryName(filePath);
how about this: 这个怎么样:
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
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而不是FileDialog,并从OK结果中获取路径。
FolderBrowserDialog browser = new FolderBrowserDialog();
string tempPath ="";
if (browser.ShowDialog() == DialogResult.OK)
{
tempPath = browser.SelectedPath; // prints path
}
Here's the simple way to do It ! 这是一个简单的方法!
string fullPath =openFileDialog1.FileName;
string directory;
directory = fullPath.Substring(0, fullPath.LastIndexOf('\\'));
这就是文件完整路径所需的全部内容
@openFileDialog1.FileName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.