gpt4 book ai didi

c# - 摆脱 CA2202

转载 作者:行者123 更新时间:2023-11-30 17:13:52 29 4
gpt4 key购买 nike

我怎样才能摆脱 CA2202 警告(CA2202:Microsoft.Usage:对象“compressedStream”可以在方法“Compression.InternalDecompress(byte [])”中多次处理。为了避免生成 System.ObjectDisposedException不应在一个对象上多次调用 Dispose)从以下代码:

        using (var compressedStream = new MemoryStream(inputData))
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
return resultStream.ToArray();
}

我尝试摆脱“using”语句并将其替换为 try/finally 模式,但随后我得到 CA2000(CA2000:Microsoft.Reliability:在方法“Compression.InternalDecompress(byte[])”中,调用 System. IDisposable.Dispose 在对象“stream”上,在所有对它的引用超出范围之前)。我试过像这样替换上面的代码:

        MemoryStream decompressedData = null;
MemoryStream stream = null;
GZipStream decompressor = null;
try
{
decompressedData = new MemoryStream();
stream = new MemoryStream(inputData);
decompressor = new GZipStream(stream, CompressionMode.Decompress, false);
stream = null;

int bytesRead = 1;
int chunkSize = 4096;
byte[] chunk = new byte[chunkSize];

while ((bytesRead = decompressor.Read(chunk, 0, chunkSize)) > 0)
{
decompressedData.Write(chunk, 0, bytesRead);
}

decompressor = null;

return decompressedData.ToArray();
}
finally
{
if (stream != null)
{
stream.Dispose();
}

if (decompressor != null)
{
decompressor.Dispose();
}

if (decompressedData != null)
{
decompressedData.Dispose();
}
}

最佳答案

这是我用的:

public class Compression
{
public Compression()
{

}

public byte[] Compress(byte[] buffer)
{
byte[] gzBuffer;

using (MemoryStream ms = new MemoryStream())
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
zip.Close();
}
ms.Position = 0;

MemoryStream outStream = new MemoryStream();

byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);

gzBuffer = new byte[compressed.Length + 4];
Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
}

return gzBuffer;
}

public byte[] Decompress(byte[] gzBuffer)
{
byte[] buffer;

using (MemoryStream ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

buffer = new byte[msgLength];

ms.Position = 0;
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
}

return buffer;
}
}

或者你可以在你的类中添加一个 pragma 语句

#pragma warning disable 2202

namespace Your.Namespace
{
...
}

#pragma warning restore 2202

关于c# - 摆脱 CA2202,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9365338/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com