簡體   English   中英

如何從 GZipStream 獲取字節數組或可讀流

[英]how to get a byte array or readable stream from a GZipStream

我想將字節數組的壓縮版本寫入 SQL Server varbinary(max) 列。

我想為 SqlClient 的命令的參數提供SqlBytes類型,並嘗試實例化該類型,因此:

// data is a byte array at this point
SqlParameter p7 = new SqlParameter("@bytes", Compress(data));
p7.SqlDbType = SqlDbType.VarBinary;


public static SqlBytes Compress(byte[] input)
{

    using (MemoryStream memstream = new MemoryStream(input))
    {    
        using (GZipStream zipped = new GZipStream(memstream, CompressionMode.Compress))
        {               
            return new SqlBytes(zipped);    
        }    
    }
}

但該命令失敗並顯示“不支持此操作”錯誤(請參見下面的跟蹤)。 因此,我需要從 GZipStream 中獲取壓縮內容並轉換為允許實例化SqlBytes類型的形式。 這是怎么做的?

注意:GZipStream 不支持讀取,因此zipped.CopyTo( myOuputMemoryStream)將不起作用。

at System.IO.Compression.GZipStream.get_Length()
at System.Data.SqlTypes.SqlBytes.get_Value()
at System.Data.SqlClient.SqlParameter.BinarySize(Object value, Boolean isSqlType)
at System.Data.SqlClient.SqlParameter.GetActualSize()
at System.Data.SqlClient.SqlParameter.ValidateTypeLengths(Boolean yukonOrNewer)
at System.Data.SqlClient.SqlCommand.SetUpRPCParameters(_SqlRPC rpc, Int32 startCount, Boolean inSchema, SqlParameterCollection parameters)
at System.Data.SqlClient.SqlCommand.BuildRPC(Boolean inSchema, SqlParameterCollection parameters, _SqlRPC& rpc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at .Form1.Save2Database(Byte[] data) 

in c:\\Users\\foo\\Documents\\Visual Studio 2013\\Projects\\Test\\Test\\Form1.cs:line 228

您傳遞給 GZipStream 構造函數的流是數據以壓縮(或解壓縮)格式寫入的流。 您應該創建一個空的內存流並使用 GZipStream 將您的字節寫入其中:

public static SqlBytes Compress(byte[] input)
{

    using (MemoryStream memstream = new MemoryStream())
    {    
        using (GZipStream zipped = new GZipStream(memstream, CompressionMode.Compress))
        {               
            zipped.Write(input, 0, input.Length);
        }   

        return new SqlBytes(memstream);             
    }
}

暫無
暫無

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

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