下面以图片文件为例加以说明。从数据库表 “图片存储”中读取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();