Categories
Technology

Insert and read images on SQL Server using C#

archive-005

Writing to SQL Server database

base64 to byte[]

// Restore the byte array.
byte[] newBytes = Convert.FromBase64String(strBase64);

Source

byte[] to SQL varbinary

byte[] buffer = File.ReadAllBytes("Path/to/your/image/");
SqlCommand command = new SqlCommand();
command.Text="INSERT INTO YOUR_TABLE_NAME (image) values (@image)";
command.Parameters.AddWithValue("@image",buffer);
command.ExecuteNonQuery();

Source

Reading from SQL Server database

Scalar to byte[]

const string sql = "SELECT data FROM files WHERE name = @name";
using (var conn = db.CreateConnection())
using (var cmd = conn.CreateTextCommand(sql))
{
    cmd.AddInParam("name", DbType.String, name);
    conn.Open();
    return cmd.ExecuteScalar() as byte[];
}

Source

byte[] to base64

// Convert the array of bytes to a base 64 string.
byte[] bytes = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
String strBase64 = Convert.ToBase64String(bytes);

// Restore the byte array.
byte[] newBytes = Convert.FromBase64String(s);

Source