1

我正在尝试使用 .NET 中的 INFLATE 压缩流DeflateStreamInvalidDataException尽管我知道我传递的数据已经被 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;
    }
4

1 回答 1

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();
        }
    }
}

现在你可能想赶上InvalidDataException- 我个人现在不会,但这样做可能是有意义的。(如有必要,我会在调用方捕获它。如有必要,您始终可以将此方法包装在另一个方法中。)

于 2012-07-02T14:09:17.290 回答