[英]Removing drive (or network name) from path in C#
从 C# 中的绝对路径中删除驱动器名称、网络路径等的最简洁(但安全)的方法是什么?
例如,转换
\\networkmachine\foo\bar
或者
C:\foo\bar
到\foo\bar
。
关于路径问题,似乎已经回答了很多问题,但我找不到我要找的东西。 我自己想到的第一个想法是使用 Path.GetFullPath() 来确保我确实在使用绝对路径,然后只使用正则表达式来查找不与另一个斜杠相邻的第一个斜杠。 但是,使用正则表达式进行路径操作似乎有点危险。
获取驱动器号/目标网络机器/等,将字符串转换为 Uri,并询问相对于驱动器/机器的路径,然后转换回字符串可能更明智吗? 还是有更好的方法?
采用
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
。
有关MSDN参考,请参阅http://msdn.microsoft.com/en-us/library/system.io.path.getpathroot.aspx
编辑 - 根据评论:
使用“string voodoo”(这不是简明恕我直言,因此不推荐)你可以这样做:
if ( ( MyPath.IndexOf (":") == 1 ) || ( MyPath.IndexOf ( "\\\\" ) == 0 ) )
{ MyPathWithoutDriveOrNetworkShare = MyPath.Substring (2); }
if ( MyPathWithoutDriveOrNetworkShare.IndexOf ( "\\" ) > 0 )
MyPathWithoutDriveOrNetworkShare = MyPathWithoutDriveOrNetworkShare.Substring ( MyPathWithoutDriveOrNetworkShare.IndexOf ( "\\" ) );
你看过DirectoryInfo类了吗?
特别是DirectoryInfo.Parent和DirectoryInfo.Root可以帮助发现根目录,以便您可以从FullName中删除它
家长: http : //msdn.microsoft.com/en-us/library/system.io.directoryinfo.parent.aspx
Root: http : //msdn.microsoft.com/en-us/library/system.io.directoryinfo.root.aspx
我认为这会奏效
public static class PathHelper
{
public static string GetPathWithoutRoot(string orgPath)
{
if (!Path.IsPathRooted(orgPath))
{
return orgPath;
}
return GetPathWithoutRoot(new DirectoryInfo(orgPath));
}
public static string GetPathWithoutRoot(DirectoryInfo dirInfo)
{
//if (dirInfo.Root == dirInfo)// try both of conditions which is correct?
if (dirInfo.Parent == null)// check here if it same
{
return string.Empty;
}
var parent = GetPathWithoutRoot(dirInfo);
if (string.IsNullOrEmpty(parent))
{
return dirInfo.Name;
}
else
{
return Path.Combine(parent, dirInfo.Name);
}
}
我不知道安全性,但我个人把它放在一个字符串中,寻找一个包含(“\\\\”)或':'并通过在它们周围进行子串解将它们从字符串中删除。
根据要求,我是这样做的:
我编写了一个帮助类PathHelper
来完成我认为提问者想知道的事情。
您可以在CodeProject上找到该库 ,我将使用的函数是PathHelper.GetDriveOrShare
,其方式类似于:
var s = @"C:\foo\bar";
var withoutRoot = s.Substring( PathHelper.GetDriveOrShare(s).Length );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.