c# 將文件保存到數據庫

最近論壇上好多人問到這個問題,其實這和保存圖片到數據庫一樣的道理,

就是把文件轉換成二進制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字節的容量.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章