Mega Code Archive

 
Categories / ASP.Net Tutorial / ADO Net Database
 

Read image from database and send to client

<%@ Page %> <%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.IO" %> <script runat="server" language="C#"> void Page_Load(Object sender, EventArgs e) {   string connectionString = "Data Source=myServer;Initial Catalog=myCatalog;User Id=user;Password=pass";   SqlConnection objConnection = new SqlConnection(connectionString);   string commandText = "SELECT Image FROM imageTable";   SqlCommand objCommand = new SqlCommand(commandText, objConnection);   SqlDataReader objReader = null;          try {     objConnection.Open();     objReader = objCommand.ExecuteReader();          if (objReader.Read())      {       Response.ContentType = "image/jpeg";       Response.BinaryWrite((Byte[])objReader["Image"]);     }   } catch (Exception exc)    {     Response.Write(exc.Message);     Response.Write("<br>This page would display an image if its connection string were set up.");   }    finally    {     if ((objConnection != null) && (objConnection.State == ConnectionState.Open))      {       objConnection.Close();     }     if (objReader != null)     objReader.Close();   } } </script>