Sep 1, 2007

Reading Binary Data Efficiently

protected void Page_Load(object sender, System.EventArgs e)
{
  string connectionString =
  WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
  SqlConnection con = new SqlConnection(connectionString);
  string SQL = "SELECT logo FROM pub_info WHERE pub_id='1389'";
  SqlCommand cmd = new SqlCommand(SQL, con);
  try
  {
    con.Open();
    SqlDataReader r =
            cmd.ExecuteReader(CommandBehavior.SequentialAccess);
    if (r.Read())
    {
      int bufferSize = 100; // Size of the buffer.
      byte[] bytes = new byte[bufferSize]; // The buffer of data.
      long bytesRead; // The number of bytes read.
      long readFrom = 0; // The starting index
      // Read the field 100 bytes at a time.
      do
      {
            bytesRead = r.GetBytes(0, readFrom, bytes, 0, bufferSize);
            Response.BinaryWrite(bytes);
            readFrom += bufferSize;
       } while (bytesRead == bufferSize);
    }
    r.Close();
}
finally
{
   con.Close();
}
}