C#中RichEdit控件,保存文本和图片到mysql数据库
分别通过内存流和RTF文件保存,个人感觉是较为完善的两种方法,希望大家可以用得到,有什么技术分享,欢迎下面留言
方法1:
//建立内存流
MemoryStream ms = new MemoryStream();
//ms.Position = 0;
//把当前的richtextbox内容包括图片和文本保存到流中
richTextBox1.SaveFile(ms, RichTextBoxStreamType.RichText);
byte[] buffer = ms.GetBuffer();
// MySqlConnectString
MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.MySqlConnectString);
string insertStr = "insert into httang_test.hxwang_richedit(image) values(@blobData);";//需要主键设置自增
MySqlParameter par = new MySqlParameter("@blobData", MySqlDbType.Blob);
par.Value = buffer;
MySqlCommand cmd = new MySqlCommand(insertStr, conn);
cmd.Parameters.Add(par);
try
{
conn.Open();
cmd.ExecuteNonQuery();
ms.Close();
ms.Dispose();
}
catch (Exception ep)
{
MessageBox.Show(ep.Message);
}
richTextBox1.Clear();
MessageBox.Show("成功插入数据库!");
}
方法2:
if ((Path.GetExtension("D:\\text")).ToLower() == ".rtf")
richTextBox1.SaveFile("D:\\text", RichTextBoxStreamType.RichNoOleObjs);
else
richTextBox1.SaveFile("D:\\text");
FileStream fs = new FileStream("D:\\text", FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] byData = br.ReadBytes((int)fs.Length);
//byte[] buffer = ms.GetBuffer();
//// MySqlConnectString
MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.MySqlConnectString);
string insertStr = "insert into httang_test.hxwang_richedit(image) values(@blobData);";//需要主键设置自增
MySqlParameter par = new MySqlParameter("@blobData", MySqlDbType.Blob);
par.Value = byData;
MySqlCommand cmd = new MySqlCommand(insertStr, conn);
cmd.Parameters.Add(par);
try
{
conn.Open();
cmd.ExecuteNonQuery();
fs.Close();
fs.Dispose();
}
catch (Exception ep)
{
MessageBox.Show(ep.Message);
}
richTextBox1.Clear();
MessageBox.Show("成功插入数据库!");
}
}