public byte[] Decompress(byte[] content) { if (content == null) throw new ArgumentNullException("content"); using (MemoryStream contentStream = new MemoryStream(content)) { using (Stream stream = new DeflateStream(contentStream, CompressionMode.Decompress)) { using (MemoryStream ms = new MemoryStream()) { const int size = 4096; byte[] buffer = new byte[size]; int count; do { count = stream.Read(buffer, 0, size); if (count > 0) { ms.Write(buffer, 0, count); } } while (count > 0); return ms.ToArray(); } } } }
public static byte[] Compress(byte[] buffer) { byte[] comp; using (var output = new MemoryStream()) { using (var deflate = new DeflateStream(output, CompressionMode.Compress)) deflate.Write(buffer, 0, buffer.Length); comp = output.ToArray(); } // Refer to http://www.ietf.org/rfc/rfc1950.txt for zlib format const byte CM = 8; const byte CINFO = 7; const byte CMF = CM | (CINFO << 4); const byte FLG = 0xDA; byte[] result = new byte[comp.Length + 6]; result[0] = CMF; result[1] = FLG; Buffer.BlockCopy(comp, 0, result, 2, comp.Length); uint cksum = ADLER32(buffer); var index = result.Length - 4; result[index++] = (byte)(cksum >> 24); result[index++] = (byte)(cksum >> 16); result[index++] = (byte)(cksum >> 8); result[index++] = (byte)(cksum >> 0); return result; }
/// <summary> /// Returns compressed version of given string. /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Compress(string str) { var barr = Encoding.Unicode.GetBytes(str + '\0'); // Why did we append a null byte... was this required? using (var mout = new MemoryStream()) { // Deflate should use optimal compression level by default (0, as defined by .NET 4.5). using (var df = new DeflateStream(mout, CompressionMode.Compress)) { // Write compressed data to memory stream. df.Write(barr, 0, barr.Length); } // Compression method int cmf = 8; // cm cmf += 7 << 4; // cinfo // Flags int flg = 2 << 6; // Compression level int n = ((cmf * 256) + flg) % 31; if (n != 0) flg += 31 - n; // Check bits // <length>;<cmf><flg><data><checksum> return string.Format("{0};{1:x02}{2:x02}{3}{4:x08}", barr.Length, cmf, flg, BitConverter.ToString(mout.ToArray()).Replace("-", "").ToLower(), ComputeAdler32(barr)); } }
/// <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); } }
/// <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; } }
/// <summary> /// Prepares a response-stream using compression-, caching- and buffering-settings /// </summary> /// <param name="context"> The context </param> /// <param name="allowZip"> set to true in case you want to honor the compression-http-headers </param> /// <param name="buffered"> set to true in case you want a BufferedStream </param> /// <param name="allowCache"> set to false in case you want to set the no-cache-http-headers </param> /// <returns> the stream to write you stuff to </returns> /// <remarks> /// Contributed by blaumeister, http://www.codeplex.com/site/users/view/blaumeiser /// </remarks> public static Stream GetResponseStream(this HttpListenerContext context, bool allowZip = true, bool buffered = true, bool allowCache = true) { if (!allowCache) { context.Response.AddHeader("Date", DateTime.UtcNow.ToString("R")); context.Response.AddHeader("Expires", DateTime.UtcNow.AddHours(-1).ToString("R")); context.Response.AddHeader("Cache-Control", "no-cache"); context.Response.AddHeader("Pragma", "no-cache"); } var stream = context.Response.OutputStream; if (allowZip) { var gzip = (context.Request.Headers["Accept-Encoding"] ?? String.Empty).Contains("gzip"); var deflate = (context.Request.Headers["Accept-Encoding"] ?? String.Empty).Contains("deflate"); context.Response.AddHeader("Vary", "Accept-Encoding"); if (gzip) { stream = new GZipStream(stream, CompressionMode.Compress); context.Response.AddHeader("Content-Encoding", "gzip"); } if (deflate) { stream = new DeflateStream(stream, CompressionMode.Compress); context.Response.AddHeader("Content-Encoding", "deflate"); } } if (buffered) stream = new BufferedStream(stream); return stream; }
public static byte[] DeflateDecompress(byte[] content, int index, int count, out int size) { size = 0; try { byte[] buffer = new byte[16384]; DeflateStream ds = new DeflateStream(new MemoryStream(content, index, count), CompressionMode.Decompress); int readsize; while (true) { readsize = ds.Read(buffer, size, buffer.Length - size); if (readsize == 0) { break; } size += readsize; byte[] newbuffer = new byte[buffer.Length * 2]; buffer.CopyTo(newbuffer, 0); buffer = newbuffer; } return buffer; } catch (Exception _Exception) { Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } return null; }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { using (var uncloseableStream = new UndisposableStream(stream)) using (var bufferedStream = new BufferedStream(uncloseableStream)) { Stream compressedStream = null; if (encodingType == "gzip") { compressedStream = new GZipStream(bufferedStream, CompressionMode.Compress, leaveOpen: true); } else if (encodingType == "deflate") { compressedStream = new DeflateStream(bufferedStream, CompressionMode.Compress, leaveOpen: true); } else throw new InvalidOperationException("This shouldn't happen, ever."); await originalContent.CopyToAsync(compressedStream); if (compressedStream != null) { compressedStream.Dispose(); } } }
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; }
public object Read(Newtonsoft.Json.JsonReader reader) { if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject) throw new Exception(); int w = ReadIntProperty(reader, "Width"); int h = ReadIntProperty(reader, "Height"); int d = ReadIntProperty(reader, "Depth"); var grid = new TileData[d, h, w]; reader.Read(); if (reader.TokenType != Newtonsoft.Json.JsonToken.PropertyName || (string)reader.Value != "TileData") throw new Exception(); ReadAndValidate(reader, Newtonsoft.Json.JsonToken.StartArray); var queue = new BlockingCollection<Tuple<int, byte[]>>(); var readerTask = Task.Factory.StartNew(() => { for (int i = 0; i < d; ++i) { reader.Read(); int z = (int)(long)reader.Value; byte[] buf = reader.ReadAsBytes(); queue.Add(new Tuple<int, byte[]>(z, buf)); } queue.CompleteAdding(); }); Parallel.For(0, d, i => { var tuple = queue.Take(); int z = tuple.Item1; byte[] arr = tuple.Item2; using (var memStream = new MemoryStream(arr)) { using (var decompressStream = new DeflateStream(memStream, CompressionMode.Decompress)) using (var streamReader = new BinaryReader(decompressStream)) { for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) grid[z, y, x].Raw = streamReader.ReadUInt64(); } } }); readerTask.Wait(); ReadAndValidate(reader, Newtonsoft.Json.JsonToken.EndArray); ReadAndValidate(reader, Newtonsoft.Json.JsonToken.EndObject); return grid; }
/// <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; }
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; } }
/// <summary> /// The GZIP decompress. /// </summary> /// <param name="data">The data to decompress.</param> /// <returns>The decompressed data</returns> public static byte[] DeflateDecompress(this byte[] data) { byte[] bytes = null; if (data != null) { using (var input = new MemoryStream(data.Length)) { input.Write(data, 0, data.Length); input.Position = 0; var gzip = new DeflateStream(input, CompressionMode.Decompress); using (var output = new MemoryStream(data.Length)) { var buff = new byte[64]; int read = gzip.Read(buff, 0, buff.Length); while (read > 0) { output.Write(buff, 0, buff.Length); read = gzip.Read(buff, 0, buff.Length); } bytes = output.ToArray(); } } } return bytes; }
public override TagCompound Load(string fileName, NbtOptions options) { TagCompound tag; BinaryTagReader reader; if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName"); if (!File.Exists(fileName)) throw new FileNotFoundException("Cannot find source file.", fileName); //Check if gzipped stream try { using (FileStream input = File.OpenRead(fileName)) { using (GZipStream gzipStream = new GZipStream(input, CompressionMode.Decompress)) { reader = new BinaryTagReader(gzipStream, NbtOptions.Header); tag = (TagCompound)reader.Read(); } } } catch (Exception) { tag = null; } if (tag != null) return tag; //Try Deflate stream try { using (FileStream input = File.OpenRead(fileName)) { using (DeflateStream deflateStream = new DeflateStream(input, CompressionMode.Decompress)) { reader = new BinaryTagReader(deflateStream, NbtOptions.Header); tag = (TagCompound)reader.Read(); } } } catch (Exception) { tag = null; } if (tag != null) return tag; //Assume uncompressed stream using (FileStream input = File.OpenRead(fileName)) { reader = new BinaryTagReader(input, NbtOptions.Header); tag = (TagCompound)reader.Read(); } return tag; }
//public static byte[] CompressStream(object obj) //{ // byte[] b; // BinaryFormatter bf = new BinaryFormatter(); // using (MemoryTributary objStream = new MemoryTributary()) // { // // using (MemoryTributary ms = new MemoryTributary()) // using (System.IO.Compression.DeflateStream objZS = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress)) // { // bf.Serialize(objZS, obj); // // ms.Position = 0; // // ms.CopyTo(objZS); // }; // b = objStream.ToArray(); // }; // return b; //} public static byte[] CompressStream(DataSet ds, bool includeSchema) { XmlWriteMode xwm; if (includeSchema) { xwm = XmlWriteMode.WriteSchema; } else { xwm = XmlWriteMode.IgnoreSchema; } byte[] b; using (MemoryTributary objStream = new MemoryTributary()) { using (System.IO.Compression.DeflateStream deflateStream = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress)) { ds.WriteXml(deflateStream, xwm); }; b = objStream.ToArray(); }; return(b); }
public WebSocket(DiscordClient client, JsonSerializer serializer, Logger logger) { _client = client; Logger = logger; _serializer = serializer; _lock = new AsyncLock(); _taskManager = new TaskManager(Cleanup); CancelToken = new CancellationToken(true); _connectedEvent = new ManualResetEventSlim(false); #if !DOTNET5_4 _engine = new WS4NetEngine(client.Config, _taskManager); #else _engine = new BuiltInEngine(client.Config); #endif _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()).GetAwaiter().GetResult(); } }; _engine.TextMessage += (s, e) => ProcessMessage(e.Message).Wait(); }
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(); } }
public static async Task<Stream> CompressAsync(CompressionType type, Stream original) { using (var ms = new MemoryStream()) { Stream compressedStream = null; if (type == CompressionType.deflate) { compressedStream = new DeflateStream(ms, CompressionMode.Compress); } else if (type == CompressionType.gzip) { compressedStream = new GZipStream(ms, CompressionMode.Compress); } if (type != CompressionType.none) { using (compressedStream) { await original.CopyToAsync(compressedStream); } //NOTE: If we just try to return the ms instance, it will simply not work // a new stream needs to be returned that contains the compressed bytes. // I've tried every combo and this appears to be the only thing that works. byte[] output = ms.ToArray(); return new MemoryStream(ms.ToArray()); } //not compressed return original; } }
static UnicodeInfo() { // First load the XML file into an XmlDocument for further processing Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Unclassified.TxEditor.UnicodeTable.deflate"); if (stream == null) { throw new ArgumentException("The embedded resource was not found in this assembly."); } characters.Clear(); List<string> categoryNames = new List<string>(); using (var ds = new DeflateStream(stream, CompressionMode.Decompress)) using (var sr = new StreamReader(ds)) { while (!sr.EndOfStream) { string line = sr.ReadLine(); if (line.Length > 4 && line[4] == '\t') { // Character definition string[] parts = line.Split('\t'); int codePoint = int.Parse(parts[0], System.Globalization.NumberStyles.HexNumber); int catIndex = int.Parse(parts[2]); characters[codePoint] = new UnicodeCharacter() { CodePoint = codePoint, Name = parts[1], Category = categoryNames[catIndex] }; } else { // Category name categoryNames.Add(line); } } } }
public byte[] Load( Stream stream, Game game, out int width, out int height, out int length ) { byte[] map = null; width = 0; height = 0; length = 0; LocalPlayer p = game.LocalPlayer; p.Spawn = Vector3.Zero; GZipHeaderReader gsHeader = new GZipHeaderReader(); while( !gsHeader.ReadHeader( stream ) ) { } using( DeflateStream gs = new DeflateStream( stream, CompressionMode.Decompress ) ) { reader = new BinaryReader( gs ); ClassDescription obj = ReadData(); for( int i = 0; i < obj.Fields.Length; i++ ) { FieldDescription field = obj.Fields[i]; if( field.FieldName == "width" ) width = (int)field.Value; else if( field.FieldName == "height" ) length = (int)field.Value; else if( field.FieldName == "depth" ) height = (int)field.Value; else if( field.FieldName == "blocks" ) map = (byte[])field.Value; else if( field.FieldName == "xSpawn" ) p.Spawn.X = (int)field.Value; else if( field.FieldName == "ySpawn" ) p.Spawn.Y = (int)field.Value; else if( field.FieldName == "zSpawn" ) p.Spawn.Z = (int)field.Value; } } return map; }
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(); } } } }
public static Byte[] Compress(this Byte[] data, CompressionAlgorithm algorithm) { //--- Define Location To Store Compressed Data ---// MemoryStream MS = new MemoryStream(); //--- Create Compression Object ---// Stream zipper; if (algorithm == CompressionAlgorithm.GZipStream) zipper = new GZipStream(MS, CompressionMode.Compress); else zipper = new DeflateStream(MS, CompressionMode.Compress); //--- Compress ---// zipper.Write(data, 0, data.Length); zipper.Flush(); zipper.Close(); zipper.Dispose(); //--- Get Compressed Data ---// Byte[] compressedData = MS.ToArray(); MS.Close(); MS.Dispose(); //--- Return Compressed Data ---// return compressedData; }
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; }
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; }
// 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; } }
/// <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); }
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; }
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()); } } } }
/// <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()); } }
private static string ExtractResource(string resource) { string path = null; try { path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream resourceStream = assembly.GetManifestResourceStream(resource)) { using (DeflateStream deflateStream = new DeflateStream(resourceStream, CompressionMode.Decompress)) { using (FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { byte[] buffer = new byte[1048576]; int bytesRead; do { bytesRead = deflateStream.Read(buffer, 0, buffer.Length); if (bytesRead != 0) fileStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); } } } return path; } catch { File.Delete(path); return null; } }
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(); }; }
void initStream() { if (deflateStream != null) { return; } deflateStream = new Compression.DeflateStream(rawStream, Compression.CompressionMode.Decompress, true); }
internal static byte[] Compress(ReadOnlySpan <byte> data) { using var val = new MemoryStream(CompressedLengthEstimate(data)); using (var compressor = new IOC.DeflateStream(val, IOC.CompressionLevel.Optimal)) { compressor.Write(data); } return(val.GetArray()); }
/// <summary> /// Initializes a new instance of the <see cref="ZlibDeflateStream"/> class. /// </summary> /// <param name="stream">The stream to compress.</param> /// <param name="compressionLevel">The compression level.</param> public ZlibDeflateStream(Stream stream, int compressionLevel) { this.rawStream = stream; // Write the zlib header : http://tools.ietf.org/html/rfc1950 // CMF(Compression Method and flags) // This byte is divided into a 4 - bit compression method and a // 4-bit information field depending on the compression method. // bits 0 to 3 CM Compression method // bits 4 to 7 CINFO Compression info // // 0 1 // +---+---+ // |CMF|FLG| // +---+---+ int cmf = 0x78; int flg = 218; // http://stackoverflow.com/a/2331025/277304 if (compressionLevel >= 5 && compressionLevel <= 6) { flg = 156; } else if (compressionLevel >= 3 && compressionLevel <= 4) { flg = 94; } else if (compressionLevel <= 2) { flg = 1; } // Just in case flg -= ((cmf * 256) + flg) % 31; if (flg < 0) { flg += 31; } this.rawStream.WriteByte((byte)cmf); this.rawStream.WriteByte((byte)flg); // Initialize the deflate Stream. CompressionLevel level = CompressionLevel.Optimal; if (compressionLevel >= 1 && compressionLevel <= 5) { level = CompressionLevel.Fastest; } else if (compressionLevel == 0) { level = CompressionLevel.NoCompression; } this.deflateStream = new System.IO.Compression.DeflateStream(this.rawStream, level, true); }
internal static byte[] Decompress(byte[] data) { using var dataStream = new MemoryStream(data); using var val = new MemoryStream(DecompressedLengthEstimate(data)); using (var compressor = new IOC.DeflateStream(dataStream, IOC.CompressionMode.Decompress)) { compressor.CopyTo(val); } return(val.GetArray()); }
internal static byte[] Decompress(byte[] data, int size) { using var dataStream = new MemoryStream(data); var output = new byte[size]; using var val = new MemoryStream(output); using var compressor = new IOC.DeflateStream(dataStream, IOC.CompressionMode.Decompress); compressor.CopyTo(val); return(output); }
static public byte[] Deflate(byte[] input) { using var deflatedStream = new System.IO.MemoryStream(); using var compressor = new System.IO.Compression.DeflateStream( deflatedStream, System.IO.Compression.CompressionMode.Compress); compressor.Write(input, 0, input.Length); compressor.Close(); return(deflatedStream.ToArray()); }
static public byte[] Inflate(IReadOnlyList <byte> input) { using var inflatedStream = new System.IO.MemoryStream(); using var deflateStream = new System.IO.Compression.DeflateStream( new System.IO.MemoryStream(input as byte[] ?? input.ToArray()), System.IO.Compression.CompressionMode.Decompress); deflateStream.CopyTo(inflatedStream); return(inflatedStream.ToArray()); }
private static byte[] ConvertDeflateToZlib(byte[] input) { using (MemoryStream deflateData = new MemoryStream(input)) using (System.IO.Compression.DeflateStream deflateStream = new System.IO.Compression.DeflateStream(deflateData, System.IO.Compression.CompressionMode.Decompress)) using (ZlibStream zlibStream = new ZlibStream(deflateStream, Ionic.Zlib.CompressionMode.Compress)) using (MemoryStream zlibData = new MemoryStream()) { zlibStream.CopyTo(zlibData); return(zlibData.ToArray()); } }
private static void CompressTemplate(string sampleFileName, ZLibCompLevel level, bool useSpan) { string filePath = Path.Combine(TestSetup.SampleDir, sampleFileName); ZLibCompressOptions compOpts = new ZLibCompressOptions() { Level = level, LeaveOpen = true, }; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (MemoryStream compMs = new MemoryStream()) using (MemoryStream decompMs = new MemoryStream()) { using (DeflateStream zs = new DeflateStream(compMs, compOpts)) { #if !NETFRAMEWORK if (useSpan) { byte[] buffer = new byte[64 * 1024]; int bytesRead; do { bytesRead = fs.Read(buffer.AsSpan()); zs.Write(buffer.AsSpan(0, bytesRead)); } while (0 < bytesRead); } else #endif { fs.CopyTo(zs); } } fs.Position = 0; compMs.Position = 0; // Decompress compMs with BCL DeflateStream using (System.IO.Compression.DeflateStream zs = new System.IO.Compression.DeflateStream(compMs, CompressionMode.Decompress, true)) { zs.CopyTo(decompMs); } decompMs.Position = 0; // Compare SHA256 Digest byte[] decompDigest = TestHelper.SHA256Digest(decompMs); byte[] fileDigest = TestHelper.SHA256Digest(fs); Assert.IsTrue(decompDigest.SequenceEqual(fileDigest)); } }
static byte[] DeflateData(Stream stream) { using (var output = new MemoryStream()) { using (var deflateStream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress, true)) { var buffer = new byte[4096]; int readBytes; while ((readBytes = deflateStream.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, readBytes); } return(output.ToArray()); } } }
public void Code(Stream inStream, Stream outStream, long inSize, long outSize, ICodeProgress progress) { using (System.IO.Compression.DeflateStream DStream = new System.IO.Compression.DeflateStream(outStream, System.IO.Compression.CompressionLevel.Fastest, true)) { if (inSize > 0) { inStream.CopyTo(DStream, (int)inSize); } else { inStream.CopyTo(DStream); } } }
public static byte[] CompressDataSet(DataSet ds) { ds.RemotingFormat = SerializationFormat.Binary; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, ds); byte[] inbyt = ms.ToArray(); System.IO.MemoryStream objStream = new MemoryStream(); System.IO.Compression.DeflateStream objZS = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress); objZS.Write(inbyt, 0, inbyt.Length); objZS.Flush(); objZS.Close(); return(objStream.ToArray()); }
internal static byte[] CompressTest(byte[] data) { IOC.DeflateStream?compressor = null; try { using var val = new MemoryStream(CompressedLengthEstimate(data)); using (compressor = new IOC.DeflateStream(val, IOC.CompressionLevel.Optimal)) { compressor.Write(data, 0, data.Length); } return(val.GetArray()); } catch (DllNotFoundException) when(compressor is not null) { GC.SuppressFinalize(compressor); throw; } }
private static byte[] DeflateCompressor(byte[] bytes) //Для старых (версии 8 и 9) и новых архивов { byte[] retVal; using (MemoryStream compressedMemoryStream = new MemoryStream()) { System.IO.Compression.DeflateStream compressStream = new System.IO.Compression.DeflateStream(compressedMemoryStream, System.IO.Compression.CompressionMode.Compress, true); compressStream.Write(bytes, 0, bytes.Length); compressStream.Close(); retVal = new byte[compressedMemoryStream.Length]; compressedMemoryStream.Position = 0L; compressedMemoryStream.Read(retVal, 0, retVal.Length); compressedMemoryStream.Close(); compressStream.Close(); } return(retVal); }
//public static byte[] CompressData(DataTable dt) //{ // dt.RemotingFormat = SerializationFormat.Binary; // return CompressStream(dt); //} private static byte[] CompressStream(DataSet obj) { byte[] b; BinaryFormatter bf = new BinaryFormatter(); using (MemoryTributary objStream = new MemoryTributary()) { using (System.IO.Compression.DeflateStream objZS = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress)) { //obj.WriteXml(objZS, XmlWriteMode.DiffGram); bf.Serialize(objZS, obj); }; b = objStream.ToArray(); }; return(b); }
public static string PostData(string url, string postData) { string result = string.Empty; try { System.Uri requestUri = new System.Uri(url); System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(requestUri); System.Text.Encoding uTF = System.Text.Encoding.UTF8; byte[] bytes = uTF.GetBytes(postData); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = (long)bytes.Length; using (System.IO.Stream requestStream = httpWebRequest.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); } using (System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse()) { using (System.IO.Stream responseStream = httpWebResponse.GetResponseStream()) { System.Text.Encoding uTF2 = System.Text.Encoding.UTF8; System.IO.Stream stream = responseStream; if (httpWebResponse.ContentEncoding.ToLower() == "gzip") { stream = new System.IO.Compression.GZipStream(responseStream, System.IO.Compression.CompressionMode.Decompress); } else { if (httpWebResponse.ContentEncoding.ToLower() == "deflate") { stream = new System.IO.Compression.DeflateStream(responseStream, System.IO.Compression.CompressionMode.Decompress); } } using (System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, uTF2)) { result = streamReader.ReadToEnd(); } } } } catch (System.Exception ex) { result = string.Format("获取信息错误:{0}", ex.Message); } return(result); }
public static string ZipBase64(string s) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, s); byte[] inbyt = ms.ToArray(); System.IO.MemoryStream objStream = new MemoryStream(); System.IO.Compression.DeflateStream objZS = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress); objZS.Write(inbyt, 0, inbyt.Length); objZS.Flush(); objZS.Close(); byte[] b = objStream.ToArray(); string ZippedBased64 = Convert.ToBase64String(b); return(ZippedBased64); }
static byte[] GetSampleDLLBytes() { byte[] buf; System.IO.Compression.DeflateStream ds; if (DLLFromMemory.Is64BitProcess) { buf = new byte[2048]; //decompress the 409 bytes below into this 2048 byte buffer (original dll file size) ds = new System.IO.Compression.DeflateStream(new System.IO.MemoryStream(new byte[409] { 0xE5, 0x94, 0x33, 0xBC, 0xDE, 0x50, 0x1C, 0x40, 0x4F, 0xF0, 0xAC, 0x6A, 0xEF, 0xBF, 0x9C, 0x6A, 0xB7, 0x4B, 0x6D, 0x5B, 0x4F, 0xC1, 0x7D, 0xFC, 0x14, 0xD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94, 0x15, 0xA8, 0xFA, 0x51, 0x23, 0xEC, 0xF6, 0x62, 0xEE, 0xA0, 0x94, 0x6B, 0x93, 0x43, 0x23, 0xDA, 0x7C, 0x04 }, false), System.IO.Compression.CompressionMode.Decompress, false); } else { buf = new byte[2048]; //decompress the 417 bytes below into this 2048 byte buffer (original dll file size) ds = new System.IO.Compression.DeflateStream(new System.IO.MemoryStream(new byte[417] { 0xED, 0xD4, 0x03, 0x8C, 0x1C, 0x01, 0x14, 0x80, 0xE1, 0x7F, 0x70, 0x36, 0x62, 0xF4, 0x5D, 0x52, 0xDB, 0x0A, 0x6A, 0xDB, 0x3A, 0x8D, 0x8E, 0xAB, 0xCC, 0xD6, 0x6E, 0x50, 0x2B, 0xD6, 0xC5, 0x4E, 0x6A, 0xDB, 0x46, 0x9C, 0x5A, 0xB1, 0x59, 0x1B, 0x83, 0xDA, 0x6D, 0x50, 0x7C, 0x0F, 0x63, 0x63, 0xC4, 0xD4, 0xF5, 0x68, 0x80, 0x0E, 0xBC, 0x7C, 0x09, 0x7B, 0xF0, 0xF5, 0xE6, 0xDB, 0xCE, 0x00, 0xB9, 0x8D, 0xF6, 0xE5, 0xB2, 0x23, 0xE3, 0x62, 0xC9, 0x1E, 0x65, 0xF8, 0xC5, 0x92, 0xF1, 0x35, 0xB5, 0x49, 0x49, 0xB8, 0xF1, 0x6A, 0xD7, 0x88, 0x8A, 0x65, 0xC4, 0x62, 0xF1, 0xE9, 0x62, 0x3A, 0xE2, 0xCE, 0x88, 0x49, 0x6D, 0x4C, 0xFA, 0x8F, 0x1A, 0x27, 0xD1, 0xB8, 0xED, 0xB4, 0xCD, 0xC9, 0xC9, 0x6C, 0x8C, 0x6F, 0x58, 0xE4, 0xC5, 0xAD, 0xBC, 0x9C, 0xF5, 0x6B, 0xC2, 0x72, 0xA7, 0xCF, 0x58, 0x93, 0xEB, 0x0D, 0x87, 0x07, 0xC3, 0x91, 0xDE, 0x70, 0x6C, 0xAD, 0x55, 0xF3, 0x66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, 0x8C, 0x48, 0xE4, 0x4D, 0x99, 0x86, 0x55, 0x0F, 0x30, 0x76, 0x5C, 0xFF, 0x71, 0x37, 0xEE, 0x2F, 0xD9, 0x3A, 0xB7, 0xA0, 0x45, 0xBF, 0x65, 0x1B, 0x9F, 0x1F, 0x6A, 0x77, 0xF9, 0x49, 0xA5, 0x02, 0xF4, 0xEF, 0x59, 0x6A, 0x3B, 0x33, 0x4B, 0x47, 0xCC, 0x19, 0xED, 0xC6, 0xEB, 0x1C, 0x6B, 0x7A, 0xB2, 0xF4, 0xF5, 0x5E, 0x06, 0xBA, 0xF1, 0xE8, 0x08, 0x27, 0x1A, 0x77, 0xE7, 0xB4, 0x89, 0x39, 0xD3, 0x4B, 0x83, 0x7D, 0x97, 0x8E, 0x75, 0x22, 0x8E, 0x91, 0x74, 0x4A, 0x3B, 0x75, 0x34, 0x6B, 0xDF, 0xCE, 0x6D, 0x9B, 0xB0, 0x4D, 0x7C, 0x0A, 0xFF, 0xB6, 0x57 }, false), System.IO.Compression.CompressionMode.Decompress, false); } ds.Read(buf, 0, buf.Length); ds.Dispose(); return(buf); }
public static bool Set(string cookieName, object cookieValue) { bool retval = true; try { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, cookieValue); byte[] inbyt = ms.ToArray(); System.IO.MemoryStream objStream = new MemoryStream(); System.IO.Compression.DeflateStream objZS = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress); objZS.Write(inbyt, 0, inbyt.Length); objZS.Flush(); objZS.Close(); byte[] b = objStream.ToArray(); string sCookieVal = Convert.ToBase64String(b); HttpCookie cook = new HttpCookie(cookieName); cook.Value = sCookieVal; cook.Expires = DateTime.Today.AddDays(30); HttpContext.Current.Response.Cookies.Add(cook); } catch { retval = false; throw; } return(retval); }
public void Extract(string basedir) { string TargetFile = System.IO.Path.Combine(basedir, FileName); using (System.IO.MemoryStream memstream = new System.IO.MemoryStream(_FileData)) { using (System.IO.Compression.DeflateStream input = new System.IO.Compression.DeflateStream(memstream, System.IO.Compression.CompressionMode.Decompress)) { // ensure the target path exists if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(TargetFile))) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(TargetFile)); } using (System.IO.FileStream output = new System.IO.FileStream(TargetFile, System.IO.FileMode.CreateNew)) { //BinaryWriter w = new BinaryWriter(fs); byte[] bytes = new byte[4096]; int n; n = 1; // anything non-zero while (n != 0) { n = input.Read(bytes, 0, bytes.Length); if (n > 0) { output.Write(bytes, 0, n); } } } if (LastModified.IsDaylightSavingTime()) { System.IO.File.SetLastWriteTime(TargetFile, LastModified.AddHours(1)); } else { System.IO.File.SetLastWriteTime(TargetFile, LastModified); } } } }
/// <summary> /// Deflate解压函数 /// JS:var details = eval_r('(' + utf8to16(zip_depress(base64decode(hidEnCode.value))) + ')')对应的C#压缩方法 /// </summary> /// <param name="strSource"></param> /// <returns></returns> public static string DeflateDecompress(this string strSource) { byte[] buffer = Convert.FromBase64String(strSource); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { ms.Write(buffer, 0, buffer.Length); ms.Position = 0; using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress)) { stream.Flush(); int nSize = 16 * 1024 + 256; //假设字符串不会超过16K byte[] decompressBuffer = new byte[nSize]; int nSizeIncept = stream.Read(decompressBuffer, 0, nSize); stream.Close(); return(System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept)); //转换为普通的字符串 } } }
public void testDeflateStream() { // make sure compression works, file should be smaller string sample = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files", "fp.log"); byte[] uncompressed = File.ReadAllBytes(sample); int before = uncompressed.Length; byte[] compressed; int after = 0; // test deflate stream compression code using (MemoryStream compressStream = new MemoryStream()) using (ZopfliStream compressor = new ZopfliStream(compressStream, ZopfliFormat.ZOPFLI_FORMAT_DEFLATE)) { compressor.Write(uncompressed, 0, before); compressor.Close(); compressed = compressStream.ToArray(); after = compressed.Length; } before.Should().BeGreaterThan(after); // make sure we can decompress the file using built-in .net byte[] decompressedBytes = new byte[before]; using (System.IO.Compression.DeflateStream decompressionStream = new System.IO.Compression.DeflateStream(new MemoryStream(compressed), System.IO.Compression.CompressionMode.Decompress)) { decompressionStream.Read(decompressedBytes, 0, before); } uncompressed.Should().Equal(decompressedBytes); // use built-in .net compression and make sure zopfil is smaller int after_builtin = 0; using (MemoryStream compressStream = new MemoryStream()) using (System.IO.Compression.DeflateStream compressor = new System.IO.Compression.DeflateStream(compressStream, System.IO.Compression.CompressionLevel.Optimal)) { compressor.Write(uncompressed, 0, before); compressor.Close(); after_builtin = compressStream.ToArray().Length; } after_builtin.Should().BeGreaterThan(after); }
/// <summary> /// Deflate压缩函数 /// </summary> /// <param name="strSource"></param> /// <returns></returns> public static string DeflateCompress(this string strSource) { if (strSource == null || strSource.Length > 8 * 1024) { throw new System.ArgumentException("字符串为空或长度太大!"); } byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strSource); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { stream.Write(buffer, 0, buffer.Length); stream.Close(); } byte[] compressedData = ms.ToArray(); ms.Close(); return(Convert.ToBase64String(compressedData)); //将压缩后的byte[]转换为Base64String } }
internal static unsafe T[] Decompress <T>(byte[] data, int size) where T : unmanaged { if (typeof(T) == typeof(byte)) { return((T[])(object)Decompress(data, size)); } using var dataStream = new MemoryStream(data); var output = GC.AllocateUninitializedArray <T>(AlignCount <T>(size)); fixed(T *outputPtr = output) { using var val = new UnmanagedMemoryStream((byte *)outputPtr, output.Length * sizeof(T)); using var compressor = new IOC.DeflateStream(dataStream, IOC.CompressionMode.Decompress); compressor.CopyTo(val); } return(output); }
public void BinaryOsmStreamTarget_ShouldWriteToDeflateStream() { using (var stream = new MemoryStream()) using (var streamCompressed = new System.IO.Compression.DeflateStream(stream, CompressionMode.Compress)) { var targetStream = new BinaryOsmStreamTarget(streamCompressed); targetStream.Initialize(); targetStream.AddRelation(new Relation() { Id = 1, ChangeSetId = 1, TimeStamp = DateTime.Now, Tags = new TagsCollection(new Tag("name", "hu?")), Members = new RelationMember[] { new RelationMember() { Id = 1, Role = "node", Type = OsmGeoType.Node }, new RelationMember() { Id = 2, Role = "way", Type = OsmGeoType.Way }, new RelationMember() { Id = 3, Role = "relation", Type = OsmGeoType.Relation } }, UserId = 1, UserName = "******", Version = 1, Visible = true }); } }
//单纯为了字符串压缩: public string Compress(string strSource) { if (strSource == null || strSource.Length > 8 * 1024) { throw new System.ArgumentException("字符串为空或长度太大!"); } System.Text.Encoding encoding = System.Text.Encoding.Unicode; byte[] buffer = encoding.GetBytes(strSource); //byte[] buffer = Convert.FromBase64String(strSource); //传入的字符串不一定是Base64String类型,这样写不行 System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true); stream.Write(buffer, 0, buffer.Length); stream.Close(); buffer = ms.ToArray(); ms.Close(); return(Convert.ToBase64String(buffer)); //将压缩后的byte[]转换为Base64String }
/// <summary> /// Deflate压缩函数 /// </summary> /// <remarks>针对JavaScript混合压缩算法</remarks> /// <param name="strSource"></param> /// <returns></returns> public static string DeflateCompress(string strSource) { if (string.IsNullOrWhiteSpace(strSource)) return string.Empty; if (strSource.Length > 8 * 1024) throw new System.ArgumentException("YSWL.Common.DEncrypt.GZip.DeflateCompress 字符串长度超过上限"); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strSource); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { stream.Write(buffer, 0, buffer.Length); stream.Close(); } byte[] compressedData = ms.ToArray(); ms.Close(); return Convert.ToBase64String(compressedData); //将压缩后的byte[]转换为Base64String } }
internal static unsafe T[] Compress <T>(ReadOnlySpan <byte> data) where T : unmanaged { if (typeof(T) == typeof(byte)) { return((T[])(object)CompressBytes(data)); } long requiredSize = CompressedLengthMax(data); long capacity = AlignCount <T>(requiredSize); if (capacity > int.MaxValue) { var resultArray = CompressBytes(data); T[] copiedResult = GC.AllocateUninitializedArray <T>(AlignCount <T>(resultArray.Length)); resultArray.AsReadOnlySpan().CopyTo(copiedResult.AsSpan().AsBytes()); return(copiedResult); } T[] result = GC.AllocateUninitializedArray <T>((int)capacity); long resultLength; fixed(T *resultPtr = result) { using var resultStream = new UnmanagedMemoryStream((byte *)resultPtr, result.Length * sizeof(T)); using var compressor = new IOC.DeflateStream(resultStream, IOC.CompressionLevel.Optimal); compressor.Write(data.ToArray(), 0, data.Length); compressor.Flush(); resultLength = resultStream.Position; } if (result.Length != resultLength) { Array.Resize(ref result, (int)resultLength); } return(result); }
/// <inheritdoc/> protected override void Dispose(bool disposing) { if (this.isDisposed) { return; } if (disposing) { // dispose managed resources if (this.deflateStream != null) { this.deflateStream.Dispose(); this.deflateStream = null; } else { // Hack: empty input? this.rawStream.WriteByte(3); this.rawStream.WriteByte(0); } // Add the crc uint crc = (uint)this.adler32.Value; this.rawStream.WriteByte((byte)((crc >> 24) & 0xFF)); this.rawStream.WriteByte((byte)((crc >> 16) & 0xFF)); this.rawStream.WriteByte((byte)((crc >> 8) & 0xFF)); this.rawStream.WriteByte((byte)(crc & 0xFF)); } base.Dispose(disposing); // Call the appropriate methods to clean up // unmanaged resources here. // Note disposing is done. this.isDisposed = true; }