ramlicious Blogs by Tina & Prabhu

November 15, 2011

Uploading file to server from a web application using C#

Filed under: .NET,C#,Programming — Prabhuram @ 2:29 pm

I’ve put a small code block to save a file to the server from a web application using C#’s FileUpload Server control.

    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />

Here is how you do it.


        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpPostedFile pf = FileUpload1.PostedFile;
            if ((pf != null) && (pf.ContentLength > 0))
            {
                try
                {
                    pf.SaveAs(string.Format("{0}\\{1}", Server.MapPath("."), System.IO.Path.GetFileName(pf.FileName)));
                    Response.Write("The file has been uploaded.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
            }
            else
            {
                Response.Write("Please select a file to upload.");
            }
        }

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress