简体   繁体   中英

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

Hello I have been following numerous tutorials online for a new project I'm working on. I am obtaining my data from filestream and I'm getting an out of memory exception at this line:

byte[] buffer = new byte[(int)sfs.Length];

What I'm doing is immediately taking the byte array and then wanting to save it to the disc. If there is not an easy way to avoid the system out of memory exception, is there a way to write to disc from the sqlFileStream avoiding creating a new byte array?

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

Here's a method that can be used to read bytes from one Stream to another Stream without regard for what type of Stream they each are.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM