你好我一直在网上关注一些我正在研究的新项目。我从文件流中获取数据,并且我在这一行得到了一个内存不足的例外:
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();
}
}
答案 0 :(得分:0)
这是一种方法,可用于从一个Stream
到另一个Stream
读取字节,而不考虑它们各自的Stream
类型。
Public Sub CopyStream(source As Stream, destination As Stream, Optional blockSize As Integer = 1024)
Dim buffer(blockSize - 1) As Byte
'Read the first block.'
Dim bytesRead = source.Read(buffer, 0, blockSize)
Do Until bytesRead = 0
'Write the current block.'
destination.Write(buffer, 0, bytesRead)
'Read the next block.'
bytesRead = source.Read(buffer, 0, blockSize)
Loop
End Sub