有条件地停止上传文件

时间:2013-08-01 20:31:03

标签: c# asp.net

如果任何文件上传控件不包含有效的扩展程序,如何停止在以下代码中上传文件?例如如果第一个控件中的文件包含有效的扩展名但第二个扩展名无效,那么我想停止上传文件并中断操作。

List<string> validExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".stl" };        
for (int i = 0; i <= hfc.Count - 1; i++)
    {
        string guidResult = System.Guid.NewGuid().ToString();

        HttpPostedFile hpf = hfc[i];
        string extension = Path.GetExtension(hfc[i].FileName);
        if (hpf.ContentLength > 0)
        {
            if (!validExtensions.Contains(extension.ToLower()))
            {
                lblMsg.Text = "Extension not supported";

            }
            else
            {
                hpf.SaveAs(Server.MapPath("files\\") + guidResult.ToString() + extension);
                lblMsg.Text = "File(s) upload successsfuly.";
            }
        }
}

2 个答案:

答案 0 :(得分:1)

您是否可以在代码中添加break语句,如下所示:

....
if (!validExtensions.Contains(extension.ToLower()))
{
    lblMsg.Text = "Extension not supported";
    break;
}
....

答案 1 :(得分:0)

在保存任何内容之前检查所有内容。一个例子是:

List<string> validExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".stl" };

if (hcf.PostedFiles.Any(x => !validExtensions.Contains(Path.GetExtension(x.FileName))))
{
     lblMsg.Text = "Extension not supported";
     return;
}    

//rest of your code here. which by the way, looks better like this:
foreach (var item in hcf.PostedFiles)
{
   string guidResult = System.Guid.NewGuid().ToString();
   item.SaveAs(Server.MapPath("files\\") + guidResult.ToString() + extension);
}