Showing posts with label filename. Show all posts
Showing posts with label filename. Show all posts

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;
    }

Thursday, May 1, 2014

Clean off the illegal characters from file name

When it comes to use file names, say, in saving reports on the disk or sending them as an attachment, they must conform OS restrictions.

Although we cannot rely on GetInvalidFileNameChars function due to its limitation, it is easy to create your own procedure that clean off the illegal characters from the given file name.

In my example I use a regular expression and a set of characters that should be replaced with the underscore by default.


/// <summary>
/// Checks for invalid characters in the filename and changes them with underscore.
/// </summary>
/// <param name="_fileName">
/// The file name value.
/// </param>
/// <param name="_char2use">
/// The character to use instead of illegal characters. Underscore by default.
/// </param>
/// <returns>
/// valid file name
/// </returns>

static client str makeFileNameValid(str _fileName, str 1 _char2use = "_")
{
    str                 pattern = "[/:*?'<>|]";
    str                 fileName;

    fileName = System.Text.RegularExpressions.Regex::Replace(_fileName, pattern, _char2use);
    fileName = strReplace(fileName , '\\', _char2use);
    return fileName;
}

I used this article.