Check whether a path is valid

前端 未结 12 1825
小蘑菇
小蘑菇 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:08

    I haven't had any problems with the code below. (Relative paths must start with '/' or '\').

    private bool IsValidPath(string path, bool allowRelativePaths = false)
    {
        bool isValid = true;
    
        try
        {
            string fullPath = Path.GetFullPath(path);
    
            if (allowRelativePaths)
            {
                isValid = Path.IsPathRooted(path);
            }
            else
            {
                string root = Path.GetPathRoot(path);
                isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
            }
        }
        catch(Exception ex)
        {
            isValid = false;
        }
    
        return isValid;
    }
    

    For example these would return false:

    IsValidPath("C:/abc*d");
    IsValidPath("C:/abc?d");
    IsValidPath("C:/abc\"d");
    IsValidPath("C:/abc<d");
    IsValidPath("C:/abc>d");
    IsValidPath("C:/abc|d");
    IsValidPath("C:/abc:d");
    IsValidPath("");
    IsValidPath("./abc");
    IsValidPath("./abc", true);
    IsValidPath("/abc");
    IsValidPath("abc");
    IsValidPath("abc", true);
    

    And these would return true:

    IsValidPath(@"C:\\abc");
    IsValidPath(@"F:\FILES\");
    IsValidPath(@"C:\\abc.docx\\defg.docx");
    IsValidPath(@"C:/abc/defg");
    IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
    IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
    IsValidPath(@"C:\\\\\abc////////defg");
    IsValidPath(@"/abc", true);
    IsValidPath(@"\abc", true);
    
    0 讨论(0)
  • 2020-11-27 04:08

    The closest I have come is by trying to create it, and seeing if it succeeds.

    0 讨论(0)
  • 2020-11-27 04:10
    private bool IsValidPath(string path)
    {
        Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
        if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
        string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
        strTheseAreInvalidFileNameChars += @":/?*" + "\"";
        Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
        if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            return false;
    
        DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
        if (!dir.Exists)
            dir.Create();
        return true;
    }
    
    0 讨论(0)
  • 2020-11-27 04:10

    Just Simply Use

    if (System.IO.Directory.Exists(path))
    {
        ...
    }
    
    0 讨论(0)
  • 2020-11-27 04:11

    Or use the FileInfo as suggested in In C# check that filename is possibly valid (not that it exists).

    0 讨论(0)
  • 2020-11-27 04:12

    Get the invalid chars from System.IO.Path.GetInvalidPathChars(); and check if your string (Directory path) contains those or not.

    0 讨论(0)
提交回复
热议问题