.NET DeflateStream用法

cyt*_*nus 1 .net deflate deflatestream inflate

我试图在.NET中使用INFLATE压缩流DeflateStream.InvalidDataException虽然我知道我传递的数据已经被DEFLATE算法正确处理(它已经过测试),但是我的代码抛出了一个.我使用DeflateStream不正确吗?我的代码如下:

public byte[] Inflate(byte[] deflateArr)
    {
        MemoryStream ms;

        // try to create a MemoryStream from a byte array
        try
        {
            ms = new MemoryStream(deflateArr);
        }
        catch (ArgumentNullException)
        {
            return null;
        }

        // create a deflatestream and pass it the memory stream
        DeflateStream ds;
        try
        {
            ds = new DeflateStream(ms, CompressionMode.Decompress);
        }
        catch (ArgumentNullException)
        {
            return null;
        }
        catch (ArgumentException)
        {
            return null;
        }

        // create a bytes array and read into it
        byte[] bytes = new byte[4096];

        try
        {
            ds.Read(bytes, 0, 4096);
        }
        catch (ArgumentNullException)
        {
            return null;
        }
        catch (InvalidOperationException)
        {
            return null;
        }
        catch (ArgumentOutOfRangeException)
        {
            return null;
        }
        catch (InvalidDataException)
        {
            return null;
        }

        // close the memory stream
        ms.Close();

        // close the deflate stream
        ds.Close();

        return bytes;
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

不你不是.

这段代码有问题:

  • 显式调用Close()而不是使用using语句.可能在这里没有害处,但是一个坏主意.
  • 捕获各种异常,你真的不应该捕获它们,因为它们表明编程错误
  • 在每个语句的基础上捕获异常,即使您在整个代码中以相同的方式处理它们(因此可以捕获更大块的异常)
  • 忽略的返回值 Stream.Read

这是一个更好的版本,假设您使用的是.NET 4(for Stream.CopyTo)

public static byte[] Inflate(byte[] inputData)
{
    using (Stream input = new DeflateStream(new MemoryStream(inputData),
                                            CompressionMode.Decompress))
    {
        using (MemoryStream output = new MemoryStream())
        {
            input.CopyTo(output);
            return output.ToArray();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可能想要抓住InvalidDataException- 我个人现在不会这样,但这样做可能有意义.(如果有必要的话,我会在主叫方面抓住它.如果需要,你总是可以将这种方法包装在另一个方法中.)