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

馋奶兔 提交于 2019-11-29 01:13:27

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 IsUncDrive(this DriveInfo info) {
  Uri uri = null;
  if ( !Uri.TryCreate(info.Name, UriKind.Absolute, out uri) ) {
    return false;
  }
  return uri.IsUnc;
}
Scott Dorman

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

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}$
  • replace 32 (2 times) with maximum allowed length of server/directory name
  • replace 10 with maximum allowed path depth (maximum count of directories)
  • extend [A-Za-z0-9_\-] (2 times) if you are missing some character allowed in server/directory name

I've successfully tested it. Enjoy!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!