有没有办法检查一个字符串是否不等于多个不同的字符串?

发布于 2024-12-09 09:42:02 字数 103 浏览 0 评论 0原文

我想通过文件扩展名验证文件上传器。如果文件扩展名不等于 .jpg、.jpeg、.gif、.png、.bmp,则抛出验证错误。

有没有办法在不循环遍历每种类型的情况下做到这一点?

I want to validate a file uploader, by file extension. If the file extension is not equal to .jpg, .jpeg, .gif, .png, .bmp then throw validation error.

Is there a way to do this without looping through each type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

独夜无伴 2024-12-16 09:42:02

只需构建一个集合 - 如果它很小,几乎任何集合都可以:

// Build the collection once (you may want a static readonly variable, for
// example).
List<string> list = new List<string> { ".jpg", ".jpeg", ".gif", ".bmp", ... };

// Later
if (list.Contains(extension))
{
    ...
}

当然,这确实会循环所有值 - 但对于小型集合,这应该不会太昂贵。对于大型字符串集合,您需要使用诸如HashSet之类的东西,这将提供更有效的查找。

Just build a collection - if it's small, just about any collection will do:

// Build the collection once (you may want a static readonly variable, for
// example).
List<string> list = new List<string> { ".jpg", ".jpeg", ".gif", ".bmp", ... };

// Later
if (list.Contains(extension))
{
    ...
}

That does loop over all the values of course - but for small collections, that shouldn't be too expensive. For a large collection of strings you'd want to use something like HashSet<string> instead, which would provide a more efficient lookup.

公布 2024-12-16 09:42:02

您可以使用 !Regex.IsMatch(extension, "^\.(jpg|jpeg|gif|png|bmp)$")

但在内部不知何故它仍然会循环

You can use !Regex.IsMatch(extension, "^\.(jpg|jpeg|gif|png|bmp)$")

but internally somehow it will still loop

鹤仙姿 2024-12-16 09:42:02

将扩展名粘贴到集合中,然后检查文件的扩展名是否在该集合中。

Stick the extensions in a collection, then check if the extension of your file is in that collection.

冷…雨湿花 2024-12-16 09:42:02

它将需要一个循环,但您可以使用 LINQ 来完成此操作(隐藏循环),

即:

using System.Linq;

private readonly string[] _matches = new[] { ".jpg", ".bmp", ".png", ".gif", ".bmp" };    

// Assumes extension is in the format ".jpg", "bmp", so trim the
// whitespace from start and end
public bool IsMatch(string extension)
{
     return _matches.Contains(extension);
}

也可以使用 Regex 来完成,但我不是 regex wizz,所以我将把它留给另一位海报:)

It will require a loop, but you can do this with LINQ (hides the loop)

ie:

using System.Linq;

private readonly string[] _matches = new[] { ".jpg", ".bmp", ".png", ".gif", ".bmp" };    

// Assumes extension is in the format ".jpg", "bmp", so trim the
// whitespace from start and end
public bool IsMatch(string extension)
{
     return _matches.Contains(extension);
}

It could also be done with Regex but I'm no regex wizz so I'll leave that to another poster :)

眼波传意 2024-12-16 09:42:02

使用以下 2 个扩展。我在 CodeProject 上的一篇文章中介绍了它们。干得好:
http://www.codeproject.com/KB/dotnet/MBGExtensionsLibrary.aspx

        public static bool In<T>(this T t, IEnumerable<T> enumerable)
        {
            foreach (T item in enumerable)
            {
                if (item.Equals(t))
                { return true; }
            }
            return false;
        }

        public static bool In<T>(this T t, params T[] items)
        {
            foreach (T item in items)
            {
                if (item.Equals(t))
                { return true; }
            }
            return false;
        }

当然,它仍然需要一个循环,但好处是您不必做这项工作。这也意味着您不必编写如下代码:

if (myString == "val1" ||
   myString == "val2" ||
   myString == "val3" ||
   myString == "val4" ||
   myString == "val5")
   {
      //Do something
   }

Use the following 2 extensions. I wrote about them in an article on CodeProject. Here you go:
http://www.codeproject.com/KB/dotnet/MBGExtensionsLibrary.aspx

        public static bool In<T>(this T t, IEnumerable<T> enumerable)
        {
            foreach (T item in enumerable)
            {
                if (item.Equals(t))
                { return true; }
            }
            return false;
        }

        public static bool In<T>(this T t, params T[] items)
        {
            foreach (T item in items)
            {
                if (item.Equals(t))
                { return true; }
            }
            return false;
        }

Of course it still requires a loop, but the good thing is you don't have to do that work. It also means you don't have to write code like this:

if (myString == "val1" ||
   myString == "val2" ||
   myString == "val3" ||
   myString == "val4" ||
   myString == "val5")
   {
      //Do something
   }
我的黑色迷你裙 2024-12-16 09:42:02

StackOverflow 上已经有答案了。 此处
但我建议您采取构建扩展列表的方式,然后再次检查每个扩展。正则表达式的成本会更高,并且内部的作用大致相同。

There's an answer to that on StackOverflow already. HERE
But I'd suggest you take the path of constructing a list of extensions and then checking agains each one of those. Regex would be more costly than that and would internally do roughly the same.

北音执念 2024-12-16 09:42:02

正则表达式。

    string fx = "jpg";
    if (!Regex.IsMatch(fx, "^\.?(jpg|jpeg|gif|png|bmp)$", RegexOptions.IgnoreCase))
    {

    }

另外,要获取文件扩展名,请使用

string fn= file.FileName;
if (fn.Contains("\\")) 
    fn= fn.Substring(fn.LastIndexOf("\\") + 1);

string fx = fn.Substring(0, fn.LastIndexOf('.'));

Regular Expression.

    string fx = "jpg";
    if (!Regex.IsMatch(fx, "^\.?(jpg|jpeg|gif|png|bmp)$", RegexOptions.IgnoreCase))
    {

    }

also, to get the file extension, use

string fn= file.FileName;
if (fn.Contains("\\")) 
    fn= fn.Substring(fn.LastIndexOf("\\") + 1);

string fx = fn.Substring(0, fn.LastIndexOf('.'));
若言繁花未落 2024-12-16 09:42:02

您可以使用 switch 语句来验证文件扩展名:

protected bool IsValidExtension(string extension)
{
  switch (extension.ToLower())
  {
    case ".jpg":
    case ".jpeg":
    case ".gif":
    case ".png":
    case ".bmp":
      return true;

    default:
      return false;
  }
}

You can use switch statement to validate file extension:

protected bool IsValidExtension(string extension)
{
  switch (extension.ToLower())
  {
    case ".jpg":
    case ".jpeg":
    case ".gif":
    case ".png":
    case ".bmp":
      return true;

    default:
      return false;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文