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

后端 未结 6 782
说谎
说谎 2020-12-15 04:09

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

6条回答
  •  粉色の甜心
    2020-12-15 04:46

    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.

提交回复
热议问题