转:C# 文件与二进制互转数据库写入读出
2012-11-14 18:40
489 查看
转载一篇文章:作者: fariyeye, 踱步在Code的尽头
C# 文件与二进制互转数据库写入读出
我们经常需要经文件存放到数据库中,可以用下现成的代码。
C# 文件与二进制互转数据库写入读出
我们经常需要经文件存放到数据库中,可以用下现成的代码。
//这个方法是浏览文件对象 private void button1_Click(object sender, EventArgs e) { //用户打开文件浏览 using (OpenFileDialog dialog = new OpenFileDialog()) { //只能单选一个文件 dialog.Multiselect = false; //选择一个文件 if (dialog.ShowDialog() == DialogResult.OK) { try { //把选择的文件路径给txtPath this.textBox1.Text = dialog.FileName; } catch (Exception ex) { //抛出异常 throw (ex); } } } } //关闭 private void button3_Click(object sender, EventArgs e) { this.Close(); } //把文件转成二进制流出入数据库 private void button2_Click(object sender, EventArgs e) { FileStream fs = new FileStream(textBox1.Text, FileMode.Open); BinaryReader br = new BinaryReader(fs); Byte[] byData = br.ReadBytes((int)fs.Length); fs.Close(); string conn = "server=.;database=testDB;Uid=sa;Pwd=sa "; SqlConnection myconn = new SqlConnection(conn); myconn.Open(); string str = "insert into pro_table (pro_name,pro_file) values('测试文件',@file)"; SqlCommand mycomm = new SqlCommand(str, myconn); mycomm.Parameters.Add("@file", SqlDbType.Binary, byData.Length); mycomm.Parameters["@file"].Value = byData; mycomm.ExecuteNonQuery(); myconn.Close(); } //从数据库中把二进制流读出写入还原成文件 private void button4_Click(object sender, EventArgs e) { string conn = "server=.;database=testDB;Uid=sa;Pwd=sa "; string str = "select pro_file from pro_table where pro_name='测试文件' "; SqlConnection myconn = new SqlConnection(conn); SqlDataAdapter sda = new SqlDataAdapter(str, conn); DataSet myds = new DataSet(); myconn.Open(); sda.Fill(myds); myconn.Close(); Byte[] Files = (Byte[])myds.Tables[0].Rows[0]["pro_file"]; BinaryWriter bw = new BinaryWriter(File.Open("D:\\2.rdlc",FileMode.OpenOrCreate)); bw.Write(Files); bw.Close(); }
相关文章推荐
- C# 单文件与二进制互转数据库写入读出(上传文件二进制方式到DB中,下载DB中的二进制文件到本地)
- C# 文件与二进制互转数据库写入读出
- C# 文件与二进制互转数据库写入读出
- C# 文件与二进制互转数据库写入读出--还包含选择文件~
- C# 文件与二进制互转数据库写入读出
- C# 文件与二进制互转数据库写入读出
- C# 文件与二进制互转数据库写入读出
- C# 多文件与二进制互转数据库写入读出(上传文件二进制方式到DB中,下载DB中的二进制文件到本地)
- C# 将long类型写入二进制文件用bw.Write(num);将其读出用long num= br.ReadInt64();
- C#读取二进制文件入数据库
- VC2010 ADO 写入二进制数据到数据库 下载二进制数据到文件
- C#读取二进制文件入数据库
- c#大文件读取和写入数据库
- QX项目实战-3.读取数据、数据写入数据库、读出数据生成新文件
- 将数据库二进制文件读出并保存到磁盘上
- C#文件基本操作3-文本数据写入读出演示
- C# 读取TXT文件并写入数据库
- [ZT]c#大文件读取和写入数据库(带进度条的源代码)
- c#大文件读取和写入数据库(带进度条的源代码)
- c#写入文件读出文件