tags:

views:

1263

answers:

3

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.

+4  A: 

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).

DannySmurf
You should check at least for "\\" to start the path, as "\this\is\not\a\unc\path" (it's not a particularly good thing to have in the path, but it's not a UNC regardless).
Michael Burr
Quite right. I've modified my answer.
DannySmurf
+1  A: 

The most accurate approach is going to be using some interop code from the shlwapi.dll

[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
internal static extern bool PathIsUNC([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);

You would then call it like this:

    /// <summary>
    /// Determines if the string is a valid Universal Naming Convention (UNC)
    /// for a server and share path.
    /// </summary>
    /// <param name="path">The path to be tested.</param>
    /// <returns><see langword="true"/> if the path is a valid UNC path; 
    /// otherwise, <see langword="false"/>.</returns>
    public static bool IsUncPath(string path)
    {
        return PathIsUNC(path);
    }

@JaredPar has the best answer using purely managed code.

Scott Dorman
+2  A: 

Try this extension method

public static bool IsUncDrive(this DriveInfo info) {
  Uri uri = null;
  if ( !Uri.TryCreate(info.Name, UriKind.Absolute, out uri) ) {
    return false;
  }
  return uri.IsUnc;
}
JaredPar
The DriveInfo object cannot be used for UNC paths. But if I change it to be an extension to DirectoryInfo, and use the FullName instead of Name, it seems to work fine.
David Eliason