如何从C#的完整路径中获取一部分?

时间:2009-05-26 20:07:38

标签: c# string directory

我有一个完整的路径,如下所示。

C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd

如何从整个部分中提取DTD“部分”?

期望的输出:

C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug‌​\DannyGoXuk.DTDs

我可以使用String的方法吗?
如果是,那么如何获取它?

11 个答案:

答案 0 :(得分:76)

使用System.IO.Path.GetDirectoryName()表示整个路径,或new DirectoryInfo(path).Parent.Name表示该文件夹的名称。


您发布的路径中没有名为“DTD”的目录。 IT看起来有一个名为"DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd"文件,但句点(。)在该路径中不是有效的目录分隔符。您的意思是"DannyGoXuk\DTDs\xhtml-math-svg-flat.dtd"吗?

如果是这种情况,给出了整个新路径,您希望这样的内容返回DTDs文件夹中的文件列表:

string path = @"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk\DTDs\xhtml-math-svg-flat.dtd";
string[] files = new DirectoryInfo(path).Parent.GetFiles();

  

在属性窗口中,我选择Build Type作为嵌入式资源。

现在我们终于明白了。选择“嵌入式资源”时,该项目将捆绑到可执行程序文件中。 没有直接路径了。而是将您的构建类型设置为“内容”,并将“复制到输出目录”设置为“始终复制”或“如果更新则复制”。

答案 1 :(得分:12)

调用

System.IO.Path.GetFileName

使用完整目录路径返回路径的最后一部分,即目录名称。 GetDirectoryName返回不需要的父目录的整个路径。

如果您有文件名,并且只想要父目录的名称:

var directoryFullPath = Path.GetDirectoryName(@"C:\DTDs\mydtd.dtd");  // C:\DTDs
var directoryName = Path.GetFileName(directoryFullPath);  // DTDs

答案 2 :(得分:9)

您还可以使用Directory从完整文件路径中获取目录:

Directory.GetParent(path).FullName

答案 3 :(得分:7)

编辑:请在下载之前仔细阅读OP的问题及其所有评论。 OP的标题问题并不完全是她想要的。我的回答给了她解决问题所需要的东西。这就是为什么她投票给答案的原因。是的,如果专门回答标题问题,Joel的回答是正确的。但在阅读她的评论之后,你会发现她并不完全是在寻找什么。感谢。

使用此...

string strFullPath = @"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd";
string strDirName; 
int intLocation, intLength;

intLength = strFullPath.Length;
intLocation = strFullPath.IndexOf("DTDs");

strDirName = strFullPath.Substring(0, intLocation); 

textBox2.Text = strDirName;

答案 4 :(得分:5)

System.IO.Path.GetFileName( System.IO.Path.GetDirectoryName( fullPath ) )

这将只返回包含该文件的文件夹的名称。

有关

C:\windows\system32\user32.dll

这将返回

system32

我推断那就是你想要的。

答案 5 :(得分:5)

使用:

string dirName = new DirectoryInfo(fullPath).name;

答案 6 :(得分:2)

您可以使用:

System.IO.Path.GetDirectoryName(path);

答案 7 :(得分:2)

您可以使用Path ...

Path.GetDirectoryName(myStr);

答案 8 :(得分:2)

不要直接使用字符串操作。而是使用Path类的GetDirectoryName

System.IO.Path.GetDirectoryName(myPath);

答案 9 :(得分:2)

使用FileInfo对象...

FileInfo info = new FileInfo(@"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd");
string directoryName = info.Directory.FullName;

该文件甚至不必存在。

答案 10 :(得分:1)

您指定的路径上的

Path.GetDirectory返回:

“C:\用户\罗尼\桌面\源头\丹尼\卡瓦斯\树干\ CSHARP \ ImportME \ XukMe \ BIN \调试”

亲自尝试:

var path = Path.GetDirectoryName(@"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd");

你的问题有点奇怪 - 没有名为DTD的目录。

相关问题