天天看點

檔案儲存到資料庫/從資料庫讀出寫成檔案

一、儲存檔案到資料庫中。

    将檔案儲存到資料庫中,實際上是将檔案轉換成二進制流後,将二進制流儲存到資料庫相應的字段中。(在SQL Server中該字段的資料類型是Image,在Access中該字段的資料類型是OLE對象,在ORCLE中是BLOB類型。

 //儲存檔案到資料庫中

 FileInfo fi=new FileInfo(fileFullPath);

 FileStream fs=fi.OpenRead();

 byte[] bytes=new byte[fs.Length];

 fs.Read(bytes,0,Convert.ToInt32(fs.Length));

 資料庫字段.Value=bytes;  

二、将檔案從資料庫中讀出

 IDataReader dr="資料庫儲存檔案字段資料"

 byte[] File=null; 

 if(dr.Read())

 {

  File=(byte[])dr[0];

 }

 FileStream fs;

 FileInfo fi=new System.IO.FileInfo(fileFullPath);

 fs=fi.OpenWrite();

 fs.Write(File,0,File.Length);

 fs.Close();

上面的代碼是将儲存在資料庫中的檔案讀取出來并儲存文指定的檔案中。

注意:

 将讀檔案的下面部分的代碼

 FileStream fs;

 FileInfo fi=new System.IO.FileInfo(fileFullPath);

 fs=fi.OpenWrite();

 fs.Write(File,0,File.Length);

 fs.Close();

修改為

 FileStream fs=new FileStream(fileFullPath,FileMode.CreateNew);

 BinaryWriter bw=new BinaryWriter(fs);

 bw.Write(file,0,file.Length);

 bw.Close();

 fs.Close();

這樣修改後,就可以解決另存為相應的檔案時,用相應的軟體不能打開的問題。