Transferring Image DataType between Two Databases

I am writing a comms application that transfers data from a main PC application to a mobile device (using SQL Mobile) and the only datatype I'm having trouble transferring is Image.

I'm using the ExecuteReader method of the SqlCommand object, and then using GetValues() of the DataReader to populate an array with the database values.



The argArray now contains the value of an image field from the main PC app, but I am unsure of how to convert this value back to a suitable format to use in a SQL Statement for the mobile database.

Essentially, I'm looking for a way to convert a value (of type Object) into a format that conforms to the SQL Server IMAGE datatype.

Can anyone help me with this?
Who is Participating?
AlexFMConnect With a Mentor Commented:
This is code fragment from the function which reads image from database:

        string strCmd = String.Format("SELECT photo FROM Photos WHERE id = {0}",
        SqlCommand cmd = new SqlCommand(strCmd, sqlConn);
        // Set the description
        lblDesc.Text = item.Desc;

        // Get bytes return from stored proc
        byte[] b = (byte[])cmd.ExecuteScalar();

Now you can call function InsertImage which requires byte[] parameter. Pass b to it, and image is copied from one database to another.

This sample shows how to convert image file to SQL database field, and how to read image from database and save to file. You can remove file handling and use read and write code fragments for your task.
AMLabelsAuthor Commented:
Without using the FileStreams, how can I convert the Object instance to a byte[]?

This code raises an InvalidCastException on the second line:

Object obj = argsArray[index];
byte[] img = (byte[])obj;

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

AMLabelsAuthor Commented:
This works, except that the SQL parameter for images must be formatted as Hex, not base 2.

Does the .NET Framework provide the functionality to convert a byte array into a Hex string?
AMLabelsAuthor Commented:
Whoops, made a mistake there. I meant to say the format of the image in SQL Statements needs to be Hex and not Base 10.
How does CodeProject sample work without this conversion?
There is poorly documented XmlConvert.ToBinHexString method which possibly does this. I understand that such conversion is required for XML files, but why does SQL need this? Please check again, I think this should work directly.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.