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 th
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.
This is my version:
public static bool IsUnc(string path)
{
string root = Path.GetPathRoot(path);
// Check if root starts with "\\", clearly an UNC
if (root.StartsWith(@"\\"))
return true;
// Check if the drive is a network drive
DriveInfo drive = new DriveInfo(root);
if (drive.DriveType == DriveType.Network)
return true;
return false;
}
The advantage of this version over @JaredPars version is that this supports any path, not just DriveInfo
.
One trick I've found is to use dInfo.FullName.StartsWith(String.Empty.PadLeft(2, IO.Path.DirectorySeparatorChar))
where dInfo is a DirectoryInfo object - if that check returns True then it's a UNC path, otherwise it's 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).
Maybe this answer can be helpful to someone who wants to validate only UNC server + share + subdirectories, for example path to network repository like
\\Server1\Share1
\\Server2\Share22\Dir1\Dir2
\\Server3
Use the following regex:
^\\\\([A-Za-z0-9_\-]{1,32}[/\\]){0,10}[A-Za-z0-9_\-]{1,32}$
32
(2 times) with maximum allowed length of server/directory name10
with maximum allowed path depth (maximum count of directories)[A-Za-z0-9_\-]
(2 times) if you are missing some character allowed in server/directory nameI've successfully tested it. Enjoy!