Reading binary object from database


Reading the binary data back from the database is not hard at all.  If you defined the column as bytea - it will be available as byte[] in your datatable.

This example fetches a row from cust_file table and puts the binary object content (column called filedata) into a Windows Forms PictureBox:



        public DataTable GetDataBinary()
        {
            Npgsql.NpgsqlConnection oConn = new Npgsql.NpgsqlConnection("Server=192.168.10.4;Port=5432;Userid=postgres;Password=stefan;Protocol=3;SSL=false;Pooling=true;MinPoolSize=1;MaxPoolSize=20;Encoding=UNICODE;Timeout=15;SslMode=Disable;Database=test");
            oConn.Open();

            DataSet oDataSet = new System.Data.DataSet();

            Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand("select * from cust_file", oConn);
            Npgsql.NpgsqlDataAdapter oAdapter = new Npgsql.NpgsqlDataAdapter(command);
            oAdapter.Fill(oDataSet);
            DataTable dt = oDataSet.Tables[0];
            oConn.Close();

            return dt;


        }




The code ablove is just a regukar read from database. Now the code to put it into the Picturebox:



            DataTable dt = GetDataBinary();
            if (dt.Rows.Count > 0)
            {
                byte[] bData2 = (byte [])dt.Rows[0]["filedata"];
                System.IO.MemoryStream oStream = new System.IO.MemoryStream(bData2);
                pictureBox1.Image = Image.FromStream(oStream);
            }


Pretty easy I must say.