直接从 sqlFileStream 保存到光盘或弄清楚如何将大数据存储在一个字节数组中

Saving to disc directyl from sqlFileStream or figuring out how to store large data inside one byte array

您好,我一直在为我正在进行的新项目关注大量在线教程。我正在从文件流获取数据,但在这一行出现内存不足异常:

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();
        }
    }

这里有一种方法,可用于将字节从一个 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