Refer this code. I have used CustomValidator.
HTML
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" multiple="multiple" />
<asp:Button Text="Upload" OnClick="Upload" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="FileUpload1"
ForeColor="red" OnServerValidate="MaxUploadValidation" ErrorMessage="Maximum 4 file can be uploaded">
</asp:CustomValidator>
</div>
</form>
C#
protected void MaxUploadValidation(object sender, ServerValidateEventArgs e)
{
e.IsValid = true;
if (this.FileUpload1.HasFile)
{
int count = Request.Files.Count;
if (count > 5)
{
e.IsValid = false;
}
}
}
protected void Upload(object sender, EventArgs e)
{
if (this.CustomValidator1.IsValid == true)
{
if (this.FileUpload1.HasFile)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
}
}
}
}
}