C#從資料庫中讀取二進位制流並生成檔案
阿新 • • 發佈:2018-11-24
下面以圖片檔案為例加以說明。從資料庫表 “圖片儲存”中讀取ID為1的圖片資料並生成圖片檔案。
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=test;charset=utf8;Uid=root;Pwd=123456");
conn.Open();
string sql = "select 內容 from 圖片儲存 limit 1";
byte[] fileBytes = null;
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.CommandText = sql;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
fileBytes = (byte[])dr.GetValue(0);
}
conn.Close();
FileStream fs = null;
string fileName = "test.jpg";//檔名可以隨意取,但是副檔名最好與原檔案保持一致
fs = File.Create(fileName, fileBytes.Length);
fs.Write(fileBytes, 0, fileBytes.Length);
fs.Close();