Saturday, July 2, 2011

Read and Write an Image into Access Database


This code is use for save the image into Access database where image column is OLE object data type:

String sourcefilepath = @"c:\windows\coffee bean.bmp";

public void File2OleDbBlob(string SourceFilePath)
        {
            try
            {
                OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb;");

                //OleDbCommand cmd = new OleDbCommand("UPDATE ImageStore SET ImageData=? WHERE SNo='1'", cn);
                OleDbCommand cmd = new OleDbCommand("insert into ImageStore(ImageData) values(?)", cn);
                System.IO.FileStream fs =
                                new System.IO.FileStream(SourceFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                Byte[] b = new Byte[fs.Length];
                fs.Read(b, 0, b.Length);
                fs.Close();
                OleDbParameter P = new OleDbParameter("@ImageData", OleDbType.VarBinary, b.Length,
                 ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, b);

                cmd.Parameters.Add(P);
                cn.Open();
                if (cmd.ExecuteNonQuery() == 1)
                    MessageBox.Show("Your images stored successfully");
                cn.Close();
            }
            catch (OleDbException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Below code is use for read the image from Access database:

String destfilepath = @"c:\mytest.bmp";

public void OleDbBlob2File(string DestFilePath)
        {
            try
            {
                int PictureCol = 0; // the column # of the BLOB field
                OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb;");

                OleDbCommand cmd = new OleDbCommand("SELECT ImageData FROM ImageStore " +
                 "WHERE SNo='1'", cn);

                cn.Open();
                OleDbDataReader dr = cmd.ExecuteReader();
                dr.Read();
                Byte[] b = new Byte[(dr.GetBytes(PictureCol, 0, null, 0, int.MaxValue))];
                dr.GetBytes(PictureCol, 0, b, 0, b.Length);
                dr.Close();
                cn.Close();
                System.IO.FileStream fs =
                 new System.IO.FileStream(DestFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);

                fs.Write(b, 0, b.Length);
                fs.Close();
                MessageBox.Show("Image written to file successfully");
            }
            catch (OleDbException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Taken from this link: http://support.microsoft.com/default.aspx?scid=kb;en-us;317016&Product=vcSnet

No comments:

Post a Comment