1

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

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

1 回答 1

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
于 2017-02-24T02:44:31.337 回答