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

David Eliason picture David Eliason · Feb 6, 2009 · Viewed 27.5k times · Source

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.

Answer

JaredPar picture JaredPar · Feb 6, 2009

Try this extension method:

public static bool IsUncPath(this string path)
{
    return Uri.TryCreate(path, UriKind.Absolute, out Uri uri) && uri.IsUnc;
}