Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to check if a path is an UNC path or a local path?

Tags:

.net

path

unc

The easiest way to check if a path is an UNC path is of course to check if the first character in the full path is a letter or backslash. Is this a good solution or could there be problems with it?

My specific problem is that I want to create an System.IO.DriveInfo-object if there is a drive letter in the path.

like image 621
David Eliason Avatar asked Feb 06 '09 15:02

David Eliason


People also ask

What is the correct UNC path?

A UNC path uses double slashes or backslashes to precede the name of the computer. The path (disk and directories) within the computer are separated with a single slash or backslash, as in the following examples. Note that in the DOS/Windows example, drive letters (c:, d:, etc.) are not used in UNC names.

How can I tell if a network path is accessible or not in C#?

How's this for a quick and dirty way to check - run the windows net use command and parse the output for the line with the network path of interest (e.g. \\vault2 ) and OK . Here's an example of the output: C:\>net use New connections will be remembered.

What is the UNC path of a mapped drive?

The UNC path is the location of the shared folders you want to connect to. For example: "\\testserver\share\test" tells the computer that's the shared folder you want to connect to on the network drive you specified in the Drive letter drop-down menu.

What are the parts of a UNC path?

UNC Name Syntax These names consist of three parts: a host device name, a share name, and an optional file path.


2 Answers

Try this extension method:

public static bool IsUncPath(this string path) {     return Uri.TryCreate(path, UriKind.Absolute, out Uri uri) && uri.IsUnc; } 
like image 65
JaredPar Avatar answered Oct 11 '22 17:10

JaredPar


Since a path without two backslashes in the first and second positions is, by definiton, not a UNC path, this is a safe way to make this determination.

A path with a drive letter in the first position (c:) is a rooted local path.

A path without either of this things (myfolder\blah) is a relative local path. This includes a path with only a single slash (\myfolder\blah).

like image 24
TheSmurf Avatar answered Oct 11 '22 17:10

TheSmurf