保存:
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 [email protected] 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();
}
}
读取:
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();
}
}