问题
How can I determine in c# if a string is a local folder string or a network string besides regular expression?
For example:
I have a string which can be "c:\a"
or "\\foldera\folderb"
回答1:
new Uri(mypath).IsUnc
回答2:
I think the full answer to this question is to include usage of the DriveInfo.DriveType property.
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
}
Test the path to see if it begins with a slash char and if it does then it is a UNC path. In this case you will have to assume that it is a network path - in reality it may not be a path that points at a different PC as it could in theory be a UNC path that points to your local machine, but this isn't likely for most people I guess, but you could add checks for this condition if you wanted a more bullet-proof solution.
If the path does not begin with a slash char then use the DriveInfo.DriveType property to determine if it is a network drive or not.
回答3:
See this answer to get the DriveInfo object for a file path
C# DriveInfo FileInfo
Use the DriveType from this to determine if it is a network path.
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.drivetype.aspx
回答4:
One more way to check whether path point to local or network drive:
var host = new Uri(@"\\foldera\folderb").Host; //returns "foldera"
if(!string.IsNullOrEmpty(host))
{
//Network drive
}
来源:https://stackoverflow.com/questions/4325712/how-can-i-determine-if-a-string-is-a-local-folder-string-or-a-network-string