C#中用于文件名验证的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/100045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular expressions in C# for file name validation
提问by Game_Overture
What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have \/:*?"<>|
characters).
什么是可以验证文本字符串以确保它是有效的 Windows 文件名的好的正则表达式?(又名没有\/:*?"<>|
字符)。
I'd like to use it like the following:
我想像下面这样使用它:
// Return true if string is invalid.
if (Regex.IsMatch(szFileName, "<your regex string>"))
{
// Tell user to reformat their filename.
}
采纳答案by Isak Savo
As answered already, GetInvalidFileNameChars should do it for you, and you don't even need the overhead of regular expressions:
正如已经回答的那样, GetInvalidFileNameChars 应该为你做,你甚至不需要正则表达式的开销:
if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
MessageBox.Show("The filename is invalid");
return;
}
回答by Drejc
Why not using the System.IO.FileInfo class, together with the DirectoryInfo class you have a set of usefull methods.
为什么不使用 System.IO.FileInfo 类,连同 DirectoryInfo 类,您将拥有一组有用的方法。
回答by Greg Beech
This isn't as simple as just checking whether the file name contains any of System.IO.Path.GetInvalidFileNameChars(as mentioned in a couple of other answers already).
这并不像检查文件名是否包含任何System.IO.Path.GetInvalidFileNameChars那样简单(如其他几个答案中所述)。
For example what if somebody enters a name that contains no invalid chars but is 300 characters long (i.e. greater than MAX_PATH) - this won't work with any of the .NET file APIs, and only has limited support in the rest of windows using the \?\ path syntax. You need context as to how long the rest of the path is to determine how long the file name can be. You can find more information about this type of thing here.
例如,如果有人输入一个不包含无效字符但长度为 300 个字符(即大于 MAX_PATH)的名称 - 这将不适用于任何 .NET 文件 API,并且仅在其余窗口中使用有限支持\\?\ 路径语法。您需要关于路径的其余部分有多长的上下文来确定文件名可以有多长。您可以在此处找到有关此类事物的更多信息。
Ultimately all your checks can reliablydo is prove that a file name is not valid, or give you a reasonable estimate as to whether it is valid. It's virtually impossible to prove that the file name is valid without actually trying to use it. (And even then you have issues like what if it already exists? It may be a valid file name, but is it valid in your scenario to have a duplicate name?)
最终,您可以可靠地做的所有检查都是证明文件名无效,或者对它是否有效给出合理的估计。如果不实际尝试使用它,几乎不可能证明文件名是有效的。(即使这样,您也会遇到诸如如果它已经存在会怎样?它可能是一个有效的文件名,但在您的场景中是否有重复的名称?)
回答by Viacheslav Ivanov
Path.GetInvalidFileNameChars - Is not a good way. Try this:
Path.GetInvalidFileNameChars - 不是一个好方法。尝试这个:
if(@"C:\A.txt".IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
MessageBox.Show("The filename is invalid");
return;
}