What is the correct way to check if a path is an UNC path or a local path?
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).
Try this extension method:
public static bool IsUncPath(this string path)
{
return Uri.TryCreate(path, UriKind.Absolute, out Uri uri) && uri.IsUnc;
}
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.