Hamed Mahdizadeh
Hamed Mahdizadeh

Reputation: 976

Decompress SQL Server compressed varbinary Array in C#

I have a table in SQL Server with a varbinary(MAX) column which is filled with SQL Compress method of JSON string with utf8 characters for example {"id": 12, title: "فروش"} in the sql I use CAST(DECOMPRESS(data) AS NVARCHAR(MAX)) and result is ok.

In the c# I use this code for decompressing the data column:

public static string Unzip(byte[] bytes)
{
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream())
    {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress))
        {
            CopyTo(gs, mso);
        }
        return Encoding.UTF8.GetString(mso.ToArray());
    }
}

But the result is an invalid string:

enter image description here

Upvotes: 1

Views: 4038

Answers (2)

Dave Black
Dave Black

Reputation: 8029

Depending on if you have the default Collations enabled in SQL, NVARCHAR will be returned as Unicode while VARCHAR will be returned as UTF-8. You could also use SQL Output Collation to force an encoding:

SELECT CAST('abc' AS varchar(5)) COLLATE Latin1_General_100_CI_AS_SC_UTF8

Upvotes: 0

Morten Bork
Morten Bork

Reputation: 1632

I believe your string is in the format "Unicode" but you are trying to use the encoding type UTF8?

Upvotes: 6

Related Questions