本文整理汇总了C#中System.IO.Compression.DeflateStream类的典型用法代码示例。如果您正苦于以下问题:C# DeflateStream类的具体用法?C# DeflateStream怎么用?C# DeflateStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DeflateStream类属于System.IO.Compression命名空间,在下文中一共展示了DeflateStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WebSocket
public WebSocket(DiscordWSClient client)
{
_client = client;
_logLevel = client.Config.LogLevel;
_loginTimeout = client.Config.ConnectionTimeout;
_cancelToken = new CancellationToken(true);
_connectedEvent = new ManualResetEventSlim(false);
_engine = new WebSocketSharpEngine(this, client.Config);
_engine.BinaryMessage += (s, e) =>
{
using (var compressed = new MemoryStream(e.Data, 2, e.Data.Length - 2))
using (var decompressed = new MemoryStream())
{
using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
zlib.CopyTo(decompressed);
decompressed.Position = 0;
using (var reader = new StreamReader(decompressed))
ProcessMessage(reader.ReadToEnd()).Wait();
}
};
_engine.TextMessage += (s, e) =>
{
/*await*/ ProcessMessage(e.Message).Wait();
};
}
示例2: NBTReader
/// <summary>
/// Creates a new NBT reader with a specified memory stream.
/// </summary>
/// <param name="memIn">The memory stream in which the NBT is located.</param>
/// <param name="version">The compression version of the NBT, choose 1 for GZip and 2 for ZLib.</param>
public NBTReader(MemoryStream memIn, int version)
{
/* Due to a file specification change on how an application reads a NBT file
* (Minecraft maps are now compressed via a z-lib deflate stream), this method
* provides backwards support for the old GZip decompression stream (in case for raw NBT files
* and old Minecraft chunk files).
*/
// meaning the NBT is compressed via a GZip stream
if (version == 1)
{
// decompress the stream
GZipStream gStream = new GZipStream(memIn, CompressionMode.Decompress);
// route the stream to a binary reader
_bRead = new BinaryReader(memIn);
}
// meaning the NBT is compressed via a z-lib stream
else if (version == 2)
{
// a known bug when deflating a zlib stream...
// for more info, go here: http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html
memIn.ReadByte();
memIn.ReadByte();
// deflate the stream
DeflateStream dStream = new DeflateStream(memIn, CompressionMode.Decompress);
// route the stream to a binary reader
_bRead = new BinaryReader(dStream);
}
}
示例3: Decompress
/// <summary>
/// Returns decompressed version of given string.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Decompress(string str)
{
if (str.Length < 12) // zlib header + checksum
throw new InvalidDataException("Compressed data seems too short.");
// Strip length and zlib header
var pos = str.IndexOf(';');
if (pos == -1)
pos = str.IndexOf("S");
str = str.Substring((pos > -1 ? 4 + pos + 1 : 4));
// Hex string to byte array
int len = str.Length;
var barr = new byte[len >> 1];
for (int i = 0; i < len; i += 2)
barr[i >> 1] = Convert.ToByte(str.Substring(i, 2), 16);
// Decompress and return
using (var mout = new MemoryStream())
using (var min = new MemoryStream(barr))
using (var df = new DeflateStream(min, CompressionMode.Decompress))
{
var read = 0;
var buffer = new byte[4 * 1024];
while ((read = df.Read(buffer, 0, buffer.Length)) > 0)
mout.Write(buffer, 0, read);
// Get result without null terminator
var result = Encoding.Unicode.GetString(mout.ToArray());
result = result.Substring(0, result.Length - 1);
return result;
}
}
示例4: Main
static void Main(string[] args)
{
GZipStream gzOut = new GZipStream(File.Create(@"C:\Writing1mb.zip"), CompressionMode.Compress);
DeflateStream dfOut = new DeflateStream(File.Create(@"C:\Writing1mb2.zip"), CompressionMode.Compress);
TextWriter tw = new StreamWriter(gzOut);
TextWriter tw2 = new StreamWriter(dfOut);
try
{
for(int i = 0; i < 1000000; i++)
{
tw.WriteLine("Writing until more than 1mb to ZIP it!");
tw2.WriteLine("Writing until more than 1mb to ZIP it!");
}
}
catch(Exception)
{
throw;
}
finally
{
tw.Close();
gzOut.Close();
tw2.Close();
dfOut.Close();
}
}
示例5: Unbind
public override UnbindResult Unbind(HttpRequestData request, IOptions options)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
var payload = Convert.FromBase64String(request.QueryString["SAMLRequest"].First());
using (var compressed = new MemoryStream(payload))
{
using (var decompressedStream = new DeflateStream(compressed, CompressionMode.Decompress, true))
{
using (var deCompressed = new MemoryStream())
{
decompressedStream.CopyTo(deCompressed);
var xml = new XmlDocument()
{
PreserveWhitespace = true
};
xml.LoadXml(Encoding.UTF8.GetString(deCompressed.GetBuffer()));
return new UnbindResult(
xml.DocumentElement,
request.QueryString["RelayState"].SingleOrDefault());
}
}
}
}
示例6: Compress
/// <summary>
/// 지정된 데이타를 압축한다.
/// </summary>
/// <param name="input">압축할 Data</param>
/// <returns>압축된 Data</returns>
public override byte[] Compress(byte[] input) {
if(IsDebugEnabled)
log.Debug(CompressorTool.SR.CompressStartMsg);
// check input data
if(input.IsZeroLength()) {
if(IsDebugEnabled)
log.Debug(CompressorTool.SR.InvalidInputDataMsg);
return CompressorTool.EmptyBytes;
}
byte[] output;
using(var outStream = new MemoryStream()) {
using(var deflate = new DeflateStream(outStream, CompressionMode.Compress)) {
deflate.Write(input, 0, input.Length);
}
output = outStream.ToArray();
}
if(IsDebugEnabled)
log.Debug(CompressorTool.SR.CompressResultMsg, input.Length, output.Length, output.Length / (double)input.Length);
return output;
}
示例7: DecompressBytes
public static byte[] DecompressBytes(CompressionType type, byte[] compressedBytes)
{
using (var ms = new MemoryStream())
{
Stream decompressedStream = null;
if (type == CompressionType.deflate)
{
decompressedStream = new DeflateStream(ms, CompressionMode.Decompress, true);
}
else if (type == CompressionType.gzip)
{
decompressedStream = new GZipStream(ms, CompressionMode.Decompress, true);
}
if (type != CompressionType.none)
{
//write the bytes to the compressed stream
decompressedStream.Write(compressedBytes, 0, compressedBytes.Length);
decompressedStream.Close();
byte[] output = ms.ToArray();
ms.Close();
return output;
}
//not compressed
return compressedBytes;
}
}
示例8: ProcessContent
private string ProcessContent(HttpWebResponse response)
{
SetEncodingFromHeader(response);
Stream s = response.GetResponseStream();
if (response.ContentEncoding.ToLower().Contains("gzip"))
s = new GZipStream(s, CompressionMode.Decompress);
else if (response.ContentEncoding.ToLower().Contains("deflate"))
s = new DeflateStream(s, CompressionMode.Decompress);
MemoryStream memStream = new MemoryStream();
int bytesRead;
byte[] buffer = new byte[0x1000];
for (bytesRead = s.Read(buffer, 0, buffer.Length); bytesRead > 0; bytesRead = s.Read(buffer, 0, buffer.Length))
{
memStream.Write(buffer, 0, bytesRead);
}
s.Close();
string html;
memStream.Position = 0;
using (StreamReader r = new StreamReader(memStream, Encoding))
{
html = r.ReadToEnd().Trim();
html = CheckMetaCharSetAndReEncode(memStream, html);
}
return html;
}
示例9: FromId
// Methods
public static Map FromId(int id)
{
lock (MapsManager.CheckLock)
{
if (MapsManager.MapId_Map.ContainsKey(id))
{
return MapsManager.MapId_Map[id];
}
string str = ((id % 10).ToString() + "/" + id.ToString() + ".dlm");
if (MapsManager.D2pFileManager.MapExists(str))
{
MemoryStream stream = new MemoryStream(MapsManager.D2pFileManager.method_1(str)) { Position = 2 };
DeflateStream stream2 = new DeflateStream(stream, CompressionMode.Decompress);
byte[] buffer = new byte[50001];
MemoryStream destination = new MemoryStream(buffer);
stream2.CopyTo(destination);
destination.Position = 0;
BigEndianReader reader = new BigEndianReader(destination);
Map map2 = new Map();
map2.Init(reader);
MapsManager.MapId_Map.Add(id, map2);
if ((MapsManager.MapId_Map.Count > 1000))
{
MapsManager.MapId_Map.Remove(MapsManager.MapId_Map.Keys.First());
}
return map2;
}
MapsManager.MapId_Map.Add(id, null);
if ((MapsManager.MapId_Map.Count > 1000))
{
MapsManager.MapId_Map.Remove(MapsManager.MapId_Map.Keys.First());
}
return null;
}
}
示例10: CompressedStream
/// <summary>
///
/// </summary>
/// <param name="contentEncoding"></param>
/// <param name="stream"></param>
/// <param name="mode"></param>
public CompressedStream(string contentEncoding, Stream stream, CompressionMode mode)
{
if (contentEncoding.IndexOf(_contentIsGZipToken, StringComparison.InvariantCultureIgnoreCase) != -1)
_gzipStream = new GZipStream(stream, mode);
else if (contentEncoding != null && contentEncoding.IndexOf(_contentIsDeflateToken, StringComparison.InvariantCultureIgnoreCase) != -1)
_deflateStream = new DeflateStream(stream, mode);
}
示例11: GetRequestAutoCookie
public string GetRequestAutoCookie(HttpWebRequest request1, ref string textRef1, ref string textRef2)
{
string str3 = "";
string str2 = "";
request1.Headers.Add(HttpRequestHeader.Cookie, this._objCookieList.ToString());
HttpWebResponse response = (HttpWebResponse) request1.GetResponse();
Stream responseStream = response.GetResponseStream();
switch (response.ContentEncoding.ToLower())
{
case "gzip":
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
break;
case "deflate":
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
break;
}
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
str3 = reader.ReadToEnd();
reader.Close();
textRef1 = response.ResponseUri.ToString();
textRef2 = response.Headers.Get("Location");
str2 = response.Headers["Set-Cookie"];
if (str2 != null && str2 != string.Empty)
{
str2 = this.ProcessCookie(str2);
}
return str3;
}
示例12: ExtractResponse
public static WebResponse ExtractResponse( HttpWebResponse response, string filename )
{
WebResponse webResponse = null;
Stream streamResponse = response.GetResponseStream();
#if !SILVERLIGHT
if ( response.ContentEncoding.ToLower().Contains( "deflate" ) )
streamResponse = new DeflateStream( streamResponse, CompressionMode.Decompress );
else if ( response.ContentEncoding.ToLower().Contains( "gzip" ) )
streamResponse = new GZipStream( streamResponse, CompressionMode.Decompress );
#endif
StreamReader streamRead = null;
try
{
webResponse = new WebResponse();
webResponse.ResponseBytes = NetworkUtils.StreamToByteArray( streamResponse );
webResponse.ResponseString = NetworkUtils.ByteArrayToStr( webResponse.ResponseBytes );
if ( !string.IsNullOrEmpty( filename ) )
MXDevice.File.Save(filename, webResponse.ResponseBytes);
}
finally
{
// Close the stream object
if ( streamResponse != null )
streamResponse.Close();
if ( streamRead != null )
streamRead.Close();
}
return webResponse;
}
示例13: Decompress
/// <summary>
/// Returns decompressed version of given string.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Decompress(string str)
{
if (str.Length < 12) // zlib header + checksum
throw new InvalidDataException("Compressed data seems too short.");
// Strip length and zlib header
var pos = str.IndexOf(';');
if (pos == -1)
pos = str.IndexOf("S");
str = str.Substring((pos > -1 ? 4 + pos + 1 : 4));
// Hex string to byte array
int len = str.Length;
var barr = new byte[len >> 1];
for (int i = 0; i < len; i += 2)
barr[i >> 1] = Convert.ToByte(str.Substring(i, 2), 16);
// Decompress and return
using (var mout = new MemoryStream())
using (var min = new MemoryStream(barr))
using (var df = new DeflateStream(min, CompressionMode.Decompress))
{
df.CopyTo(mout);
return Encoding.Unicode.GetString(mout.ToArray());
}
}
示例14: GetAddonInfoData
public static byte[] GetAddonInfoData(CharacterSession session, byte[] packedData, int packedSize, int unpackedSize)
{
// Check ZLib header (normal mode)
if (packedData[0] == 0x78 && packedData[1] == 0x9C)
{
var unpackedAddonData = new byte[unpackedSize];
if (packedSize > 0)
{
using (var inflate = new DeflateStream(new MemoryStream(packedData, 2, packedSize - 6), CompressionMode.Decompress))
{
var decompressed = new MemoryStream();
inflate.CopyTo(decompressed);
decompressed.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < unpackedSize; i++)
unpackedAddonData[i] = (byte)decompressed.ReadByte();
}
}
return unpackedAddonData;
}
else
{
Log.Error($"Wrong AddonInfo for Client '{session.GetClientInfo()}'.");
session.Dispose();
}
return null;
}
示例15: Compress
public static byte[] Compress(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException("data");
}
using (var output = new MemoryStream())
{
// ZLib Header 0x78 0x9C
output.WriteByte(0x78);
output.WriteByte(0x9C);
using (var input = new MemoryStream(data))
{
using (var compressionStream = new DeflateStream(output, CompressionMode.Compress, true))
{
input.CopyTo(compressionStream);
compressionStream.Close();
// Adler32 hash of the uncompressed data
var adler32 = new Adler32();
adler32.Update(data);
byte[] hash = BitConverter.GetBytes((int) adler32.Value);
Array.Reverse(hash);
output.Write(hash, 0, hash.Length);
return output.ToArray();
}
}
}
}