你好!
我写了个简单的示例你可以参考一下。
string filePath = @"C:\01.docx";
byte[] fileContent;
// 读取文件流
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
fileContent = new byte[fs.Length];
fs.Read(fileContent, 0, (int)fs.Length);
}
/* 表结构
CREATE TABLE Files (
Id UNIQUEIDENTIFIER NOT NULL
, FileName NVARCHAR(50) NOT NULL
, FileContent VARBINARY(MAX) NOT NULL
, PRIMARY KEY (ID))
*/
// 写入到数据库
Guid newId = Guid.NewGuid();
using (SqlConnection conn = new SqlConnection(@"Server=XP01\SQLEXPRESS;Database=X;Integrated Security=SSPI"))
{
SqlCommand comm = new SqlCommand("INSERT INTO Files (Id, FileName, FileContent) VALUES (@Id, @FileName, @FileContent)", conn);
comm.Parameters.AddWithValue("@Id", newId);
comm.Parameters.AddWithValue("@FileName", Path.GetFileName(filePath));
comm.Parameters.AddWithValue("@FileContent", fileContent);
conn.Open();
comm.ExecuteNonQuery();
}
// 从数据读取并写入到硬盘上
using (SqlDataAdapter da = new SqlDataAdapter(
"SELECT * FROM Files",
@"Server=XP01\SQLEXPRESS;Database=X;Integrated Security=SSPI"))
{
DataSet ds = new DataSet();
da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
//MemoryStream ms = new MemoryStream(
string newFileName = "DB_" + row["FileName"].ToString();
string newFilePath = Path.Combine(@"C:\", newFileName);
byte[] newFileContent = (byte[])row["FileContent"];
using (FileStream fs = new FileStream(newFilePath, FileMode.Create, FileAccess.Write))
{
fs.Write(newFileContent, 0, newFileContent.Length);
}
}
}
知识改变命运,奋斗成就人生!