Insert BLOB into Postgresql with .NET


In this scenario I will create a functionality pretty much the same as in this article on Inserting binary objects into MySQL

Lets start this by creating the table



CREATE TABLE cust_file
(
  id serial NOT NULL,
  customer_id integer,
  filename character varying(255),
  filedata bytea,
  contenttype character varying(255),
  length integer,
  CONSTRAINT custfile_pk PRIMARY KEY (id)
) 
WITHOUT OIDS;



Next step is simply writing the code. We will try to create a C# function with the following header:

public void File_Save(string sConnString, int nCustId, byte[] bData, string sName, string sContentType, int nContentLength);

I bet you are wondering about the byte[] thing. It is of course the binary data - and if you are using ASP.NET and file upload then this article will show you how to create a byte array out of the uploaded file.

In this example I will simple read a file from disk, using this function:



        public byte[] FileToArray(string sFilePath)
        {
            FileStream fs = new FileStream(args[0], FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(new BufferedStream(fs));
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);
            br.Close();
            fs.Close();
            return bytes;
        }

The mimetype might not be needed, depends on your specific scenario of course - in a webapplication you typically get the mimetype from the uploading process - but I have a function to read the mimetype from just the filename which is usable from Windows Forms apps for example.