@Allrameest answer using Path.GetInvalidFileNameChars()
is probably the one you should use.
What I wanted to address is the fact that your regex is actually wrong or very ineffective (I don't know what exectly you wanted to do).
So, using:
var regex = new Regex(@"^[\\\/\:\*\?\'\<\>\|]+$");
mean you match a string which consists ONLY of "forbidden" characters (BTW, I think single quote '
is not invalid). Is it what you want? Don't think so. What you did is:
^
start of the string
[...]+
invalid characters only (at least once)
$
end of the string
Maybe you wanted @"^[^...]+$"
(hat used twice)?
Anyway, solution for your problem (with regex) is:
- don't use
^
or $
just try to find any of those and bomb out quickly
- in raw string (the one starting with
@"
) you escape double quotes by doubling it.
So, the right regex is:
var regex = new Regex(@"[\\\/\:\*\?\""\<\>\|]");
if (regex.Match(filename).Success) {
throw new ArgumentException("Bad filename");
}
Just find any and bomb out.
UPDATE by @JohnLBevan
var regex = new Regex(
"[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]");
if (regex.Match(filename).Success) {
throw new ArgumentException("Bad filename");
}
(Not using string.Format(...)
as this Regex should be static and precompiled anyway)