Regex to validate filename [closed]
If filename has another characters then this a-zA-Z0-9!@$%^&*()_+=-[]{}';,.
we must replace them in some character or delete.
resultString = Regex.Replace(subjectString, @"[^a-zA-Z0-9!@$%^&*()_+=[\]{}';,.-]", "X");
should do it.
Explanation: I copied your list of characters and pasted them into a negated character class ([^...]
). I just had to make two minor modifications: Escaping the closing bracket (\]
) and putting the dash at the end of the string.
using System.Linq;
using System.IO;
string path = ...;
IEnumerable<char> invalidChars = Enumerable.Concat(
Path.GetInvalidFileNameChars(),
Path.GetInvalidPathChars());
foreach (char c in invalidChars)
{
path = path.Replace(c, ''); // or any char you want
}
精彩评论