Monday, 31 December 2012

File Upload in asp.net using C#

File Upload in asp.net using C#

Step 1)  Create a Webpage name it as FileUploadDemo

Step 2)  Add FileUpload Control and Button control
<div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUploads" runat="server" OnClick="btnUploads_Click" Text="Upload" />
    </div>

Step 3) Create a uploads folder in WebApplication

Step 4) If Website  is in IIS Directory(for ex:C:\inetpub\wwwroot\Test\WebApplication1) ,make sure all access permissions set   for
IIS_IUSRS(machinename\IIS_USRS) user i.e read and write permissions for uploads folder
.

Step 5) If Website is file based, no need to worry about permissions

Step 6) Once it is done, Add Event Handler for btnUpload shown above

     protected void btnUploads_Click(object sender, EventArgs e)
        {
            try
            {
                System.IO.Stream stream = FileUpload1.FileContent;
                System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                String content = reader.ReadToEnd();
                System.IO.File.AppendAllText(MapPath("uploads/" + FileUpload1.FileName), content);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }