Save: private void btnSave_Click (object sender, System. EventArgs e)
{
FileStream stream = null;
SqlConnection conn = null;
SqlCommand cmd = null;
Try
{
RichTextBox1.SaveFile ("temp. rtf ");
Stream = new FileStream ("temp. rtf", FileMode. Open, FileAccess. Read );
Int size = Convert. ToInt32 (stream. Length );
Byte [] rtf = new Byte [size];
Stream. Read (rtf, 0, size );
Conn = new SqlConnection ("Database = Northwind; Integrated Security = true ;");
Conn. Open ();
Cmd = new SqlCommand ("UPDATE Employees SET Photo = @ Photo WHERE EmployeeID = 1", conn );
SqlParameter paramRTF =
New SqlParameter ("@ Photo ",
SqlDbType. Image,
Rtf. Length,
ParameterDirection. Input,
False,
0, 0, null,
DataRowVersion. Current,
Rtf );
Cmd. Parameters. Add (paramRTF );
Int rowsUpdated = Convert. ToInt32 (cmd. ExecuteNonQuery ());
MessageBox. Show (String. Format ("{0} rows updated", rowsUpdated ));
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
Finally
{
If (stream! = Null) stream. Close ();
If (cmd! = Null) cmd. Parameters. Clear ();
If (conn! = Null) conn. Close ();
}
}
Read: private void btnLoad_Click (object sender, System. EventArgs e)
{
RichTextBox1.Clear ();
SqlConnection cn = null;
SqlCommand cmd = null;
SqlDataReader reader = null;
Try
{
Cn = new SqlConnection ("Database = Northwind; Integrated Security = true ;");
Cn. Open ();
Cmd = new SqlCommand ("SELECT Photo FROM Employees WHERE EmployeeID = 1", cn );
Reader = cmd. ExecuteReader ();
Reader. Read ();
If (reader. HasRows)
{
If (! Reader. IsDBNull (0 ))
{
Byte [] rtf = new Byte [Convert. ToInt32 (reader. GetBytes (0, 0, null, 0, Int32.MaxValue)];
Long bytesReceived = reader. GetBytes (0, 0, rtf, 0, rtf. Length );
ASCIIEncoding encoding = new ASCIIEncoding ();
RichTextBox1.Rtf = encoding. GetString (rtf, 0, Convert. ToInt32 (bytesReceived ));
}
}
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
Finally
{
If (reader! = Null) reader. Close ();
If (cn! = Null) cn. Close ();
}
}