zahed zahed -4 years ago 228
ASP.NET (C#) Question

Validation for Multiple File upload using C# web forms

I want to validate multiple uploaded files. It should accept only .png and .jpg files. Below is my code:

protected void uploadFile_Click(object sender, EventArgs e)
if (multipleFile.HasFiles)
string filenameWithPath = string.Empty;
foreach (HttpPostedFile uploadedFile in multipleFile.PostedFiles)
filenameWithPath = System.IO.Path.Combine(
uploadedFile.SaveAs( filenameWithPath );
ltStatusText.Text += "File-<b>"
+ uploadedFile.FileName
+ "</b> uploaded successfully.<br>";

Answer Source

I got answer.

Below is Design code:

<form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
    <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="UploadMultipleFiles" />
    <hr />
    <asp:Label ID="Information" runat="server" ForeColor="Green" />

Below is C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;

public partial class CS : System.Web.UI.Page
 protected void UploadMultipleFiles(object sender, EventArgs e)
  foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
    string fileName = Path.GetFileName(postedFile.FileName);

        Regex reg = new Regex(@"^.*\.(jpg|JPG|jpeg|PNG|png)$");
        if (reg.IsMatch(fileName))
            postedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
            Information.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
            Information.Text = "files have been uploaded fail , please check file format!";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download