[英]How to get a part from the full path in C#?
我有一个完整的路径,如下所示。
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
的方法吗?
如果是,那么如何获取它?
将System.IO.Path.GetDirectoryName()
用于整个路径,或使用new DirectoryInfo(path).Parent.Name
作为该文件夹的名称。
您发布的路径中没有名为“DTD”的目录。 它看起来像有一个文件名为"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作为嵌入式资源。
现在我们终于明白了。 选择“嵌入式资源”时,该项目将捆绑到可执行程序文件中。 没有直接的路径了 。 而是将您的构建类型设置为“内容”并将“复制到输出目录”设置为“始终复制”或“如果更新则复制”。
调用
System.IO.Path.GetFileName
使用完整目录路径返回路径的最后一部分,即目录名称。 GetDirectoryName
返回不需要的父目录的完整路径。
如果您有文件名,并且只想要父目录的名称:
var directoryFullPath = Path.GetDirectoryName(@"C:\DTDs\mydtd.dtd"); // C:\DTDs
var directoryName = Path.GetFileName(directoryFullPath); // DTDs
您还可以使用Directory从完整文件路径获取目录:
Directory.GetParent(path).FullName
编辑:请在下载之前仔细阅读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;
使用:
string dirName = new DirectoryInfo(fullPath).name;
System.IO.Path.GetFileName( System.IO.Path.GetDirectoryName( fullPath ) )
这将只返回包含该文件的文件夹的名称。
对于
C:\windows\system32\user32.dll
这将回来
system32
我推断那就是你想要的。
您可以使用:
System.IO.Path.GetDirectoryName(path);
你可以使用Path ...
Path.GetDirectoryName(myStr);
不要直接使用字符串操作。 而是使用Path类的GetDirectoryName
:
System.IO.Path.GetDirectoryName(myPath);
使用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;
该文件甚至不必存在。
您指定的路径上的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的目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.