c# 将文件保存到数据库

来源:互联网 发布:淘宝bug反馈 编辑:程序博客网 时间:2024/05/10 13:24

最近论坛上好多人问到这个问题,其实这和保存图片到数据库一样的道理,

就是把文件转换成二进制byte数组,保存到数据库就可以了.

以Access数据库为例,数据表有两个字段,主键ID,和File字段类型为OLE对象.

private void SaveFile()
        
{
            Form1 frm 
= new Form1();
            FileStream filestream 
= new FileStream(Application.StartupPath + "/a.txt", FileMode.Open, FileAccess.Read);
            BinaryReader filerd 
= new BinaryReader(filestream,Encoding .Default );
            
byte[] filebyte = new byte[filestream.Length];
            filerd.Read(filebyte, 
0, (int)filestream.Length);

            frm.OpenConn();

            OleDbCommand comm 
= new OleDbCommand("insert into file  (id,file) Values(@fid,@file) ", frm.dbconn );
            comm.Parameters.AddWithValue(
"@fid""0001");
            comm.Parameters.AddWithValue(
"@file", DBNull.Value);
            comm.Parameters[
"@file"].Value = filebyte;
            comm.ExecuteNonQuery();            

        }

        
private void ReadFile()
        
{
            Form1 frm 
= new Form1();
            frm.OpenConn();
            OleDbCommand comm 
= new OleDbCommand("select * from file", frm.dbconn);
            OleDbDataAdapter da 
= new OleDbDataAdapter(comm);
            DataSet ds 
= new DataSet();
            da.Fill(ds);
            
byte[] filebyte = (byte[])ds.Tables[0].Rows[0]["File"];
          
//  System.Text.Encoding mycode = new System.Text.Encoding();
            this.richTextBox1.AppendText(Encoding.Default.GetString(filebyte));
        }

其中Form1 frm = new Form1();是因为我在Form1中已经定义了OleDbConnetion,没有必要再重新定义了.

将frm.OpenConn(); frm.dbconn 换成你自己的连接数据库代码就可以了.

如果是sql数据库,将字段该为image;是因为image字段可存储超过8000字节的容量.

 

原创粉丝点击