如何在c#中确定字符串是否是正则表达式之外的本地文件夹字符串或网络字符串?
例如:
我有一个字符串,可以是"c:\a"
或"\\foldera\folderb"
答案 0 :(得分:20)
new Uri(mypath).IsUnc
答案 1 :(得分:8)
请参阅此答案以获取文件路径的DriveInfo对象
使用此类型的DriveType确定它是否为网络路径。
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.drivetype.aspx
答案 2 :(得分:8)
我认为这个问题的完整答案是包含DriveInfo.DriveType属性的使用。
public static bool IsNetworkPath(string path)
{
if (!path.StartsWith(@"/") && !path.StartsWith(@"\"))
{
string rootPath = System.IO.Path.GetPathRoot(path); // get drive's letter
System.IO.DriveInfo driveInfo = new System.IO.DriveInfo(rootPath); // get info about the drive
return driveInfo.DriveType == DriveType.Network; // return true if a network drive
}
return true; // is a UNC path
}
测试路径以查看它是否以斜杠char开头,如果是,则它是UNC路径。在这种情况下,您将不得不假设它是一个网络路径 - 实际上它可能不是指向不同PC的路径,因为理论上它可能是指向本地计算机的UNC路径,但这不是可能对大多数人来说,但是如果你想要一个更加防弹的解决方案,你可以添加对这种情况的检查。
如果路径不以斜杠字符开头,则使用DriveInfo.DriveType属性确定它是否是网络驱动器。
答案 3 :(得分:0)
检查路径是指向本地驱动器还是网络驱动器的另一种方法:
var host = new Uri(@"\\foldera\folderb").Host; //returns "foldera"
if(!string.IsNullOrEmpty(host))
{
//Network drive
}