Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a string is a local folder string or a network string?

Tags:

c#

unc

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"

like image 556
user526731 Avatar asked Dec 01 '10 15:12

user526731


People also ask

How do you check if a path is a directory in C#?

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.

How do you determine if a path is valid?

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.


1 Answers

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.

like image 79
Kev Avatar answered Oct 11 '22 17:10

Kev