我正在编写一个小工具,它从选择文件开始,然后我需要选择一个文件夹。我想将文件夹默认设置为所选文件所在的位置。
OpenFileDialog.FileName
返回完整路径和文件名-我想要的是只获取路径部分(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方法可以做到这一点,或者我需要使用regex, split, trim,
等?
发布于 2009-01-13 13:57:59
使用System.IO
中的Path
类。它包含用于操作文件路径的有用调用,包括执行所需操作的GetDirectoryName
,它返回文件路径的目录部分。
使用方法很简单。
string directoryPath = Path.GetDirectoryName(filePath);
发布于 2013-02-15 20:23:15
这样如何:
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
发布于 2012-07-11 01:13:11
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}
https://stackoverflow.com/questions/439007
复制相似问题