网络上的读写OLE对象的代码是多,不过多是转载的,大部分人从来都没实际测试过,只是COPY来COPY去。我重来没看到一个真正可以运行的东东。
没办法,只有自力更生,花了一点时间出了点研究成果,写到这里做个记录。
关键代码如下:
******* void button1_Click(object sender, EventArgs e) //写入图片
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "All Files|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName = dlg.FileName;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
//pictureBox1.Image = Image.FromFile(fileName);
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\db1.mdb" + ";Persist Security Info=True");
cn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO list1(pic) VALUES(@img)", cn);
((OleDbParameter)cmd.Parameters.Add("@img", OleDbType.Binary)).Value = buffer;
cmd.ExecuteNonQuery();
}
}
******* void button2_Click(object sender, EventArgs e) //读取图片
{
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\db1.mdb" + ";Persist Security Info=True");
cn.Open();
OleDbDataAdapter oda = new OleDbDataAdapter("select pic from list1 where 编号=10", cn);
DataTable dt = new DataTable();
oda.Fill(dt);
cn.Close();
byte[] buffer = dt.Rows[0][0] as byte[];
MemoryStream ms = new MemoryStream(buffer);
pictureBox1.Image = Image.FromStream(ms);
}
******* void button3_Click(object sender, EventArgs e) //写入长文本
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "TXT Files|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName = dlg.FileName;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
//pictureBox1.Image = Image.FromFile(fileName);
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\db1.mdb" + ";Persist Security Info=True");
cn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO list1(pic) VALUES(@img)", cn);
((OleDbParameter)cmd.Parameters.Add("@img", OleDbType.Binary)).Value = buffer;
cmd.ExecuteNonQuery();
}
}
******* void button4_Click(object sender, EventArgs e) //载入长文本
{
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\db1.mdb" + ";Persist Security Info=True");
cn.Open();
OleDbDataAdapter oda = new OleDbDataAdapter("select pic from list1 where 编号=12", cn);
DataTable dt = new DataTable();
oda.Fill(dt);
cn.Close();
byte[] buffer = dt.Rows[0][0] as byte[];
//MemoryStream ms = new MemoryStream(buffer);
richTextBox1.Text =System.Text.Encoding.Default.GetString(buffer);
}