// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.IO; using System.Data; using System.Data.SqlClient; class MainClass { public static void Main(string[] args) { // connect SqlConnection con = new SqlConnection("server=ARNEPC2\\ARNEPC2RUN;Integrated Security=SSPI;database=TestMSDE"); con.Open(); // create table SqlCommand cre = new SqlCommand("CREATE TABLE imgtest (id INTEGER PRIMARY KEY,img IMAGE)", con); cre.ExecuteNonQuery(); // file -> byte array Stream imgfile = new FileStream(@"C:\blue.jpg", FileMode.Open); byte[] imgdata = new byte[(int)imgfile.Length]; imgfile.Read(imgdata, 0, imgdata.Length); imgfile.Close(); // insert SqlCommand ins = new SqlCommand("INSERT INTO imgtest VALUES(@id,@img)", con); ins.Parameters.Add("@id", SqlDbType.Int); ins.Parameters.Add("@img", SqlDbType.Image); ins.Parameters["@id"].Value = 1; ins.Parameters["@img"].Value = imgdata; ins.ExecuteNonQuery(); // select SqlCommand sel = new SqlCommand("SELECT img FROM imgtest WHERE id = @id", con); sel.Parameters.Add("@id", SqlDbType.Int); sel.Parameters["@id"].Value = 1; byte[] imgdata2 = (byte[])sel.ExecuteScalar(); // drop table SqlCommand drp = new SqlCommand("DROP TABLE imgtest", con); drp.ExecuteNonQuery(); // byte array -> file Stream imgfile2 = new FileStream(@"C:\blue2.jpg", FileMode.Create); imgfile2.Write(imgdata2, 0, imgdata2.Length); imgfile2.Close(); // disconnect con.Close(); } }