Mega Code Archive

 
Categories / ASP.Net / Asp Control
 

FileUpload Control

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="Default_aspx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">     <title>FileUpload Control</title> </head> <body>     <form id="form1" runat="server">     <div>     <h1>FileUpload Control</h1>      <asp:FileUpload ID="FileUpload1" runat="server" />      <br />      <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />      <asp:Button ID="btnDisplay" runat="server" Text="Display" OnClick="btnDisplay_Click" />      <br />      <br />      <asp:Label ID="lblMessage" runat="server" />      <asp:Label ID="lblDisplay" runat="server" />     </div>     </form> </body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; public partial class Default_aspx : System.Web.UI.Page  {   protected void btnSave_Click(object sender, EventArgs e){      string str = "";      if (FileUpload1.HasFile) {        try {          str += "Uploading file: " + FileUpload1.FileName;          FileUpload1.SaveAs("c:\\" + FileUpload1.FileName);          str += "<br/>Saved As: " + FileUpload1.PostedFile.FileName;          str += "<br/>File Type: " + FileUpload1.PostedFile.ContentType;          str += "<br/>File Length (bytes): " + FileUpload1.PostedFile.ContentLength;          str += "<br/>PostedFile File Name: " + FileUpload1.PostedFile.FileName;        } catch (Exception ex) {          str += "<br/><b>Error</b><br/>Unable to save c:\\" + FileUpload1.FileName + "<br/>" + ex.Message;        }      } else {        str = "No file uploaded.";      }      lblMessage.Text = str;      lblDisplay.Text = "";    }   protected void btnDisplay_Click(object sender, EventArgs e)   {     string str = "<u>File:  " + FileUpload1.FileName + "</u><br/>";       if (FileUpload1.HasFile)     {       try       {         Stream stream = FileUpload1.FileContent;         StreamReader reader = new StreamReader(stream);         string strLine = "";         do         {           strLine = reader.ReadLine();           str += strLine;         } while (strLine != null);       }       catch (Exception ex)       {         str += "<br/><b>Error</b><br/>Unable to display " + FileUpload1.FileName + "<br/>" + ex.Message;       }     }     else     {       str = "No file uploaded.";     }     lblDisplay.Text = str;     lblMessage.Text = "";   } }