-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathByteCompression.cs
55 lines (54 loc) · 1.48 KB
/
ByteCompression.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.IO;
using System.IO.Compression;
namespace NetFrameworkHelper
{
/// <summary>
/// Common byte array extension methods.
/// </summary>
/// <remarks>Byte array extension methods specific to Image operations are located in the Image Helper.</remarks>
public static class ByteCompression
{
/// <summary>
/// Compress a byte array using Gzip
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] Compress(this byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data), "The byte array was passed as null");
}
using (MemoryStream compressedStream = new MemoryStream())
using (GZipStream zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
zipStream.Write(data, 0, data.Length);
zipStream.Close();
return compressedStream.ToArray();
}
}
/// <summary>
/// Decompress a byte array using gzip
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] Decompress(this byte[] data)
{
try
{
using (MemoryStream memStream = new MemoryStream(data))
using (GZipStream zipStream = new GZipStream(memStream, CompressionMode.Decompress))
using (MemoryStream resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
zipStream.Dispose();
byte[] retArray = resultStream.ToArray();
return retArray;
}
}
catch {/*not compressed*/}
return data;
}
}
}