c# read binary data from sqlserver and output data-stream

From: http://dbtutorials.com/advanced/retrieving-binary-sql-cs.aspx

c# read binary data from sqlserver

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class ShowImage : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		try
		{
			int PictureID = Convert.ToInt32(Request.QueryString["ID"]);

			using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
			{
				const string SQL = "SELECT [MIME], [BinaryData] FROM [BinaryTable] WHERE [ID] = @ID";
				SqlCommand myCommand = new SqlCommand(SQL, myConnection);
				myCommand.Parameters.AddWithValue("@ID", PictureID);

				myConnection.Open();
				SqlDataReader myReader = myCommand.ExecuteReader();

				if (myReader.Read())
				{
					Response.ContentType = myReader["MIME"].ToString();
					Response.BinaryWrite((byte[]) myReader["BinaryData"]);
				}

				myReader.Close();
				myConnection.Close();
			}
		}
		catch (Exception ex)
		{
			Response.Write(ex.ToString());
		}
	}
}

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s