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"
The Directory static class in the System.IO namespace provides the Exists() method to check the existence of a directory on the disk. This method takes the path of the directory as a string input, and returns true if the directory exists at the specified path; otherwise, it returns false.
get(path) method returns a path. However if the path is not valid, then it throws InvalidPathException. For example Path. get("C://test.txt") will return true while Path.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With