Check whether a path is valid

前端 未结 12 1870
小蘑菇
小蘑菇 2020-11-27 03:39

I am just wondering: I am looking for a way to validate if a given path is valid. (Note: I do not want to check if a file is existing! I only want to proof the validity

12条回答
  •  执念已碎
    2020-11-27 04:32

    There are plenty of good solutions in here, but as none of then check if the path is rooted in an existing drive here's another one:

    private bool IsValidPath(string path)
    {
        // Check if the path is rooted in a driver
        if (path.Length < 3) return false;
        Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
        if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
    
        // Check if such driver exists
        IEnumerable allMachineDrivers = DriveInfo.GetDrives().Select(drive => drive.Name);
        if (!allMachineDrivers.Contains(path.Substring(0, 3))) return false;
    
        // Check if the rest of the path is valid
        string InvalidFileNameChars = new string(Path.GetInvalidPathChars());
        InvalidFileNameChars += @":/?*" + "\"";
        Regex containsABadCharacter = new Regex("[" + Regex.Escape(InvalidFileNameChars) + "]");
        if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            return false;
        if (path[path.Length - 1] == '.') return false;
    
        return true;
    }
    

    This solution does not take relative paths into account.

提交回复
热议问题