簡體   English   中英

從sqlFileStream保存到disc directyl或者弄清楚如何在一個字節數組中存儲大數據

[英]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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM