Copy between two streams in .net 2.0

2019-05-02 02:43发布

I have been using the following code to Compress data in .Net 4.0:

public static byte[] CompressData(byte[] data_toCompress)
{

    using (MemoryStream outFile = new MemoryStream())
    {
        using (MemoryStream inFile = new MemoryStream(data_toCompress))
        using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
        {
            inFile.CopyTo(Compress);

        }
        return outFile.ToArray();
    }

}

However, in .Net 2.0 Stream.CopyTo method is not available. So, I tried making a replacement:

public static byte[] CompressData(byte[] data_toCompress)
{

    using (MemoryStream outFile = new MemoryStream())
    {
        using (MemoryStream inFile = new MemoryStream(data_toCompress))
        using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
        {
            //inFile.CopyTo(Compress);
            Compress.Write(inFile.GetBuffer(), (int)inFile.Position, (int)(inFile.Length - inFile.Position));
        }
        return outFile.ToArray();
    }

}

The compression fails, though, when using the above attempt - I get an error saying:

MemoryStream's internal buffer cannot be accessed.

Could anyone offer any help on this issue? I'm really not sure what else to do here.

Thank you, Evan

7条回答
Deceive 欺骗
2楼-- · 2019-05-02 03:24

Since you have access to the array already, why don't you do this:

using (MemoryStream outFile = new MemoryStream())
{
    using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
    {
        Compress.Write(data_toCompress, 0, data_toCompress.Length);
    }
    return outFile.ToArray();
}

Most likely in the sample code you are using inFile.GetBuffer() will throw an exception since you do not use the right constructor - not all MemoryStream instances allow you access to the internal buffer - you have to look for this in the documentation:

Initializes a new instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified, and the ability to call GetBuffer set as specified.

This should work - but is not needed anyway in the suggested solution:

using (MemoryStream inFile = new MemoryStream(data_toCompress, 
                                              0, 
                                              data_toCompress.Length, 
                                              false, 
                                              true))
查看更多
登录 后发表回答