this is how I do it to save the image inside the BLOB/Image DB field.
/// <summary>
/// Saves the file into a BLOB/Image field in the DB
/// This uses an UPDATE command, therefore the record must alreay exist in the DB
/// </summary>
/// <param name="aTableName"></param>
/// <param name="aFieldName"></param>
/// <param name="aWhereClause"></param>
/// <param name="aFileName"></param>
/// <returns></returns>
public bool SaveToBLOB(string aTableName, string aFieldName, string aWhereClause, string aFileName)
{
string sSQL = string.Format("UPDATE {0} SET {1}=@{1} WHERE {2}", aTableName, aFieldName, aWhereClause);
using (SqlCommand oComm = new SqlCommand(sSQL, m_Conn))
{
byte[] wFileAsByteArr = CDBConn.GetFileAsByteArray(aFileName);
oComm.Parameters.Add("@" + aFieldName, SqlDbType.Image, wFileAsByteArr.Length).Value = wFileAsByteArr;
return oComm.ExecuteNonQuery() > 0;
}
}
And this is how I retrieve it:
///
/// extract the first field (BLOB) of the specified SQL Command and save it as a file
///
///
///
/// true if the file was created and false otherwise
public bool ExtractBLOB(string aSQLCommand, string aFileName)
{
using (SqlCommand oComm = CreateCommand())
{
oComm.CommandText = aSQLCommand;
oComm.CommandType = CommandType.Text;
// Create a file to hold the output.
using (System.IO.FileStream fs = new System.IO.FileStream(aFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
{
byte[] b = (byte[])oComm.ExecuteScalar();
if (b != null)
{
bw.Write(b);
bw.Flush();
return true;
}
else
return false;
}
}
}
}
Where the aSQLCommand will be: SELECT MyImageField FROM TableABC WHERE ...