开发者

Regex to validate filename [closed]

开发者 https://www.devze.com 2023-01-14 09:46 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years a开发者_如何学Cgo.

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

精彩评论

暂无评论...
验证码 换一张
取 消