使用C#从数据库读取图像二进制流的代码

工作需要,要判断一个老的数据库中image存放的数据类型,写了一段代码,放在这里供大家参考。除数据库部分需要大家修改一下以外,其它全部调试正常。里面有意思的是省却了connection的close方法,而用了另一种方式取代,希望大家能注意一下。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace image
{
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.ListBox listBox1;
  private System.ComponentModel.Container components = null;

  public Form1()
  {

   InitializeComponent();

  }

  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码

  private void InitializeComponent()
  {
   this.button1 = new System.Windows.Forms.Button();
   this.listBox1 = new System.Windows.Forms.ListBox();
   this.SuspendLayout();
 
   this.button1.Location = new System.Drawing.Point(104, 216);
   this.button1.Name = "button1";
   this.button1.TabIndex = 0;
   this.button1.Text = "button1";
   this.button1.Click += new System.EventHandler(this.button1_Click);
  
   this.listBox1.ItemHeight = 12;
   this.listBox1.Location = new System.Drawing.Point(0, 0);
   this.listBox1.Name = "listBox1";
   this.listBox1.Size = new System.Drawing.Size(200, 172);
   this.listBox1.TabIndex = 1;
 
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(292, 273);
   this.Controls.Add(this.listBox1);
   this.Controls.Add(this.button1);
   this.Name = "Form1";
   this.Text = "Image";
   this.Load += new System.EventHandler(this.Form1_Load);
   this.ResumeLayout(false);

  }
  #endregion

 
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void Form1_Load(object sender, System.EventArgs e)
  {
  
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
   string myConnectionString="workstation id=820SERVER;packet size=4096;integrated security=SSPI;data source=820SERVER;persist security info=False;initial catalog=images";
   string mySelectQuery="SELECT * FROM VBADGE";
   CreateMySqlDataReader(mySelectQuery,myConnectionString);
  }

  public void CreateMySqlDataReader(string mySelectQuery,string myConnectionString)
  {
   byte[] tmp;
   SqlConnection myConnection = new SqlConnection(myConnectionString);
   SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
   myConnection.Open();
   SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
   myReader.Read();
   tmp=(byte[])myReader[0];
   FileStream fs = new FileStream("tmp.tmp",FileMode.CreateNew);
   BinaryWriter w = new BinaryWriter(fs);
   w.Write(tmp);
   w.Close();   
   myReader.Close();
  }

 }
}

原文地址:https://www.cnblogs.com/pipisong/p/127120.html