Regular expression for valid filename

While what the OP asks is close to what the currently accepted answer uses (^[\w\-. ]+$), there might be others seeing this question who has even more specific constraints.

First off, running on a non-US/GB machine, \w will allow a wide range of unwanted characters from foreign languages, according to the limitations of the OP.

Secondly, if the file extension is included in the name, this allows all sorts of weird looking, though valid, filenames like file .txt or file...txt.

Thirdly, if you're simply uploading the files to your file system, you might want a blacklist of files and/or extensions like these:

web.config, hosts, .gitignore, httpd.conf, .htaccess

However, that is considerably out of scope for this question; it would require all sorts of info about the setup for good guidance on security issues. I thought I should raise the matter none the less.

So for a solution where the user can input the full file name, I would go with something like this:

^[a-zA-Z0-9](?:[a-zA-Z0-9 ._-]*[a-zA-Z0-9])?\.[a-zA-Z0-9_-]+$

It ensures that only the English alphabet is used, no beginning or trailing spaces, and ensures the use of a file extension with at least 1 in length and no whitespace.

I've tested this on Regex101, but for future reference, this was my "test-suite":

## THE BELOW SHOULD MATCH
web.config
httpd.conf
test.txt
1.1
my long file name.txt

## THE BELOW SHOULD NOT MATCH - THOUGH VALID
æøå.txt
hosts
.gitignore
.htaccess

To validate a file name i would suggest using the function provided by C# rather than regex

if (filename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
}

This is the correct expression:

string regex = @"^[\w\-. ]+$";

\w is equivalent of [0-9a-zA-Z_].

Tags:

C#

Regex