將檔案存入資料庫是常見需求,本質是將檔案轉為二進位位元組陣列(byte[]),寫入對應欄位:SQL Server 用 Image 型別,Access 用 OLE Object 型別。
FileInfo + FileStream 讀取檔案為 byte[]SqlCommand/OleDbCommand 及參數化查詢SqlDbType.Image / OleDbType.BinaryExecuteNonQuery() 完成寫入FileInfo fi = new FileInfo(fileName);
FileStream fs = fi.OpenRead();
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
fs.Close();
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandType = CommandType.Text;
if (cn.State == ConnectionState.Closed) 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();
OleDbCommand cm = new OleDbCommand();
cm.Connection = cn;
// ...
OleDbParameter spFile = new OleDbParameter("@file", OleDbType.Binary);
spFile.Value = bytes;
cm.Parameters.Add(spFile);
string sql = "UPDATE t_mail SET attachfilename=@attachfilename, attachfile=@attachfile WHERE mailid=" + mailId;
SqlCommand myCommand = new SqlCommand(sql, new SqlConnection(ConnStr));
string path = fl_name.PostedFile.FileName;
string filename = path.Substring(path.LastIndexOf("\\") + 1);
myCommand.Parameters.Add("@attachfilename", SqlDbType.VarChar).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];
fileStream.Read(fileContent, 0, intFileSize);
fileStream.Close();
myCommand.Parameters["@attachfile"].Value = fileContent;
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
FileStream 分塊讀寫或 FILESTREAM 型別(SQL Server 2008+)using 區塊自動管理連線與資源釋放