您好,我一直在为我正在从事的一个新项目在线关注大量教程。我正在从文件流中获取数据,并且在这一行出现内存不足异常:
byte[] buffer = new byte[(int)sfs.Length];
我正在做的是立即获取字节数组,然后想将其保存到光盘上。如果没有一种简单的方法来避免系统内存不足异常,有没有办法从 sqlFileStream 写入磁盘以避免创建新的字节数组?
string cs = @”Data Source=<your server>;Initial Catalog=MyFsDb;Integrated Security=TRUE”;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlTransaction txn = con.BeginTransaction();
string sql = “SELECT fData.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT(), fName FROM MyFsTable”;
SqlCommand cmd = new SqlCommand(sql, con, txn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string filePath = rdr[0].ToString();
byte[] objContext = (byte[])rdr[1];
string fName = rdr[2].ToString();
SqlFileStream sfs = new SqlFileStream(filePath, objContext, System.IO.FileAccess.Read);
**byte[] buffer = new byte[(int)sfs.Length];**
sfs.Read(buffer, 0, buffer.Length);
sfs.Close();
string filename = @”C:\Temp\” + fName;
System.IO.FileStream fs = new System.IO.FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Write);
fs.Write(buffer, 0, buffer.Length);
fs.Flush();
fs.Close();
}
rdr.Close();
txn.Commit();
con.Close();
}
}