如何确定字符串是本地文件夹字符串还是网络字符串?

如何在c#中确定字符串是否是正则表达式之外的本地文件夹字符串或网络字符串?

例如:

我有一个字符串,可以是"c:\a""\\foldera\folderb"

new Uri(mypath).IsUnc

请参阅此答案以获取文件路径的DriveInfo对象

C#DriveInfo FileInfo

使用此中的DriveType确定它是否是网络路径。

http://msdn.microsoft.com/en-us/library/system.io.driveinfo.drivetype.aspx

我认为这个问题的完整答案是包括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路径,但这不是可能对大多数人来说,但是如果你想要一个更加防弹的解决方案,你可以添加对这种情况的检查。

如果路径不以斜杠char开头,则使用DriveInfo.DriveType属性来确定它是否是网络驱动器。

检查路径是指向本地驱动器还是网络驱动器的另一种方法:

 var host = new Uri(@"\\foldera\folderb").Host; //returns "foldera" if(!string.IsNullOrEmpty(host)) { //Network drive }