从C#中的路径中删除驱动器(或网络名称) [英] Removing drive (or network name) from path in C#
问题描述
从C#的绝对路径中删除驱动器名称,网络路径等的最简洁(最安全)方法是什么?
例如,转换
\\networkmachine\foo\bar
或
C:\foo\bar
到\foo\bar
.
关于路径问题,似乎已经回答了很多问题,但是我找不到我想要的东西.我想到的第一个想法是使用Path.GetFullPath()来确保我确实在使用绝对路径,然后仅使用正则表达式来查找与另一个斜杠不相邻的第一个斜杠.但是,使用正则表达式进行路径操作似乎有些危险.
There seem to be a good number of questions already answered with regards to path matters, but I couldn't quite find what I was looking for. My own first thought that came to mind was to use Path.GetFullPath() to ensure I'm indeed working with an absolute path and then to just use a regular expression to find the first slash that isn't next to another one. However, using a regular expression to do path manipulation seems slightly dangerous.
获取驱动器号/目标网络机器/等,将字符串转换为Uri,并要求相对于驱动器/机器的路径,然后再转换回字符串,是否更明智?还是有更好的方法?
Would it perhaps be wiser to get the drive letter/target network machine/etc, convert the strings to Uri, and ask for the path relative to the drive/machine, and then convert back to strings? Or is there an even better approach?
推荐答案
使用
string MyPath = @""; // \\networkmachine\foo\bar OR C:\foo\bar
string MyPathWithoutDriveOrNetworkShare = MyPath.Substring (Path.GetPathRoot(MyPath).Length);
C:\foo\bar
的结果将是foo\bar
,\\networkmachine\foo\bar
的结果将是bar
.
Result for C:\foo\bar
would be foo\bar
and for \\networkmachine\foo\bar
would be bar
.
有关MSDN参考,请参见 http://msdn. microsoft.com/en-us/library/system.io.path.getpathroot.aspx
For MSDN reference see http://msdn.microsoft.com/en-us/library/system.io.path.getpathroot.aspx
编辑-根据评论:
使用字符串伏都教"(IMHO并不简洁,因此不建议使用),您可以执行以下操作:
With "string voodoo" (which is NOT concise IMHO and thus NOT recommended) you could do this:
if ( ( MyPath.IndexOf (":") == 1 ) || ( MyPath.IndexOf ( "\\\\" ) == 0 ) )
{ MyPathWithoutDriveOrNetworkShare = MyPath.Substring (2); }
if ( MyPathWithoutDriveOrNetworkShare.IndexOf ( "\\" ) > 0 )
MyPathWithoutDriveOrNetworkShare = MyPathWithoutDriveOrNetworkShare.Substring ( MyPathWithoutDriveOrNetworkShare.IndexOf ( "\\" ) );
这篇关于从C#中的路径中删除驱动器(或网络名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!