Click here to Skip to main content
15,887,464 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi I am a C# fresher to C#. I am developing a page to upload a zip file to server with less than 10MB. Now i am able to upload the zip file to server, but still unable to validate the file type(only allow zip file) and file size.


here is my code:
XML
<system.web>
    <httpRuntime maxRequestLength="10240" executionTimeout="1500"/>
  </system.web>


XML
<form id="form1" method="post" enctype="multipart/form-data" runat="server">

    <input type="file" id="File1" name="File1" />
    <br/>
    <input type="submit" value="Upload Data File" name="cmdSubmit"/>
    </form>



Behind code:
C#
protected void Page_Load(object sender, EventArgs e)
       {
           foreach (string key in Request.Files.Keys)
           {
               HttpPostedFile file = Request.Files.Get(key);
               string fn = Path.GetFileNameWithoutExtension(file.FileName) +
               DateTime.Now.ToString("ddMMyyyy") + Path.GetExtension(file.FileName);
               file.SaveAs(Server.MapPath("./data/" + fn));

               Response.Write("<br>" + fn + " is uploaded!");

           }

       }

Thanks in advance.
Posted
Updated 3-Apr-11 1:27am
v2

1 solution

The answer for your question is within your code

check for extension by string comparison
C#
if(string.Compare(Path.GetExtension(file.FileName),".zip",true)!=0)
{
ShowMessage("You Can upload only zip files");
return;
}

void ShowMessage(msg)
{
ClientScript.RegisterStartupScript(GetType(),"msg","alert('"+ msg +"');",true)
}


and for fie size
if((file.FileBytes.LongLength/(1024*1024))>10)
{
ShowMessage("You can upload upto 10Mb");
}


--Pankaj
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900