Tuesday, February 8, 2022

How to validate filename with regular expressions

 I took the idea from this forum https://stackoverflow.com/questions/62771/how-do-i-check-if-a-given-string-is-a-legal-valid-file-name-under-windows

We can use regular expressions to check if a given file name is valid.


    /// <summary>
    /// Validates a filename for incorrect characters
    /// </summary>
    /// <param name = "_fileName"></param>
    /// <returns></returns>
    public boolean checkFileName(Filename _fileName)
    {
        var bad = System.IO.Path::GetInvalidFileNameChars();
        var esc = System.Text.RegularExpressions.Regex::Escape(new System.String(bad));
        var exp = new System.Text.RegularExpressions.Regex("[" + esc + "]");
        
        if (exp.IsMatch(_fileName))
        {
            return checkFailed(strFmt("@SYS339524")); // The specified filename is invalid.
        }
        return true;
    }

No comments: