C# 檔案儲存到資料庫中或者從資料庫中讀取檔案

來源:互聯網
上載者:User

其實,方法非常的簡單,只是可能由於這些朋友剛剛開始編程不久,一時沒有找到方法而已。
下面介紹一下使用C#來完成此項任務。
首先,介紹一下儲存檔案到資料庫中。
將檔案儲存到資料庫中,實際上是將檔案轉換成二進位流後,將二進位流儲存到資料庫相應的欄位中。在SQL Server中該欄位的資料類型是Image,在Access中該欄位的資料類型是OLE對象。 複製代碼 代碼如下://儲存檔案到SQL Server資料庫中
FileInfo fi=new FileInfo(fileName);
FileStream fs=fi.OpenRead();
byte[] bytes=new byte[fs.Length];
fs.Read(bytes,0,Convert.ToInt32(fs.Length));
SqlCommand cm=new SqlCommand();
cm.Connection=cn;
cm.CommandType=CommandType.Text;
if(cn.State==0) cn.Open();
cm.CommandText="insert into "+tableName+"("+fieldName+") values(@file)";
SqlParameter spFile=new SqlParameter("@file",SqlDbType.Image);
spFile.Value=bytes;
cm.Parameters.Add(spFile);
cm.ExecuteNonQuery()
//儲存檔案到Access資料庫中
FileInfo fi=new FileInfo(fileName);
FileStream fs=fi.OpenRead();
byte[] bytes=new byte[fs.Length];
fs.Read(bytes,0,Convert.ToInt32(fs.Length));
OleDbCommand cm=new OleDbCommand();
cm.Connection=cn;
cm.CommandType=CommandType.Text;
if(cn.State==0) cn.Open();
cm.CommandText="insert into "+tableName+"("+fieldName+") values(@file)";
OleDbParameter spFile=new OleDbParameter("@file",OleDbType.Binary);
spFile.Value=bytes;
cm.Parameters.Add(spFile);
cm.ExecuteNonQuery()
//儲存用戶端檔案到資料庫
sql="update t_mail set attachfilename=@attachfilename,attachfile=@attachfile where mailid="+mailid;
myCommand = new SqlCommand(sql, new SqlConnection(ConnStr));
string path = fl_name.PostedFile.FileName;
string filename=path.Substring(path.LastIndexOf("\\")+1,path.Length-path.LastIndexOf("\\")-1);
myCommand.Parameters.Add("@attachfilename",SqlDbType.VarChar);
myCommand.Parameters["@attachfilename"].Value=filename;
myCommand.Parameters.Add("@attachfile",SqlDbType.Image);
Stream fileStream = fl_name.PostedFile.InputStream;
int intFileSize = fl_name.PostedFile.ContentLength;
byte[] fileContent = new byte[intFileSize];
int intStatus = fileStream.Read(fileContent,0,intFileSize); //檔案讀取到fileContent數組中
myCommand.Parameters["@attachfile"].Value=((byte[])fileContent);
fileStream.Close();
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();

代碼中的fileName是檔案的完整名稱,tableName是要操作的表名稱,fieldName是要儲存檔案的欄位名稱。
兩段代碼實際上是一樣的,只是操作的資料庫不同,使用的對象不同而已。
接著,在說說將檔案從資料庫中讀取出來,只介紹從SQL Server中讀取。 複製代碼 代碼如下:SqlDataReader dr=null;
SqlConnection objCn=new SqlConnection();
objCn.ConnectionString="Data Source=(local);User ID=sa;Password=;Initial Catalog=Test";
SqlCommand cm=new SqlCommand();
cm.Connection=cn;
cm.CommandType=CommandType.Text;
cm.CommandText="select "+fieldName+" from "+tableName+" where ID=1";
dr=cm.ExecuteReader();
byte[] File=null;
if(dr.Read())
{
File=(byte[])dr[0];
}
FileStream fs;
FileInfo fi=new System.IO.FileInfo(fileName);
fs=fi.OpenWrite();
fs.Write(File,0,File.Length);
fs.Close();

上面的代碼是將儲存在資料庫中的檔案讀取出來並儲存文fileName指定的檔案中。
在使用上面的代碼時,別忘了添加System.Data.SqlClient和System.IO引用。
修改:
將讀檔案的下面部分的代碼 複製代碼 代碼如下:FileStream fs;
FileInfo fi=new System.IO.FileInfo(fileName);
fs=fi.OpenWrite();
fs.Write(File,0,File.Length);
fs.Close();
修改為
FileStream fs=new FileStream(fileName,FileMode.CreateNew);
BinaryWriter bw=new BinaryWriter(fs);
bw.Write(File,0,File.Length);
bw.Close();
fs.Close();

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.