/// <summary> /// Looks up the given file in the Mix database and returns a <see cref="MemoryStream"/> for it. /// </summary> /// <param name="fileName">The file to find.</param> /// <returns>Returns a <see cref="MemoryStream"/> if found, <see cref="null"/> otherwise.</returns> public static Stream GetStream(string fileName) { Console.WriteLine("Mix: get stream for \"{0}\"...", fileName); if (File.Exists(Path.Combine("data", fileName))) { return(new MemoryStream(File.ReadAllBytes(Path.Combine("data", fileName)))); } if (!fileList.ContainsKey(fileName)) { throw new FileNotFoundException("File " + fileName + " was not found in the MIX files."); } //MemoryStream ret; var entry = fileList[fileName]; using (var mStream = new BinaryReader(File.Open(entry.MixFile, FileMode.Open))) { mStream.BaseStream.Seek(entry.Offset, SeekOrigin.Begin); if (!entry.IsCompressed) { return(new MemoryStream(mStream.ReadBytes(entry.Length))); } else { var cStream = new MemoryStream(mStream.ReadBytes(entry.Length)); var decompressor = new System.IO.Compression.DeflateStream(cStream, System.IO.Compression.CompressionMode.Decompress); var outStream = new MemoryStream(); decompressor.CopyTo(outStream); //ret = new byte[outStream.Length]; outStream.Seek(0, SeekOrigin.Begin); return(outStream); //outStream.Read(ret, 0, ret.Length); } } }
} // End Sub CompressFile public static void DeflateCompressFile(string FileToCompress, string CompressedFile) { //byte[] buffer = new byte[1024 * 1024 * 64]; byte[] buffer = new byte[1024 * 1024]; // 1MB using (System.IO.FileStream sourceFile = System.IO.File.OpenRead(FileToCompress)) { using (System.IO.FileStream destinationFile = System.IO.File.Create(CompressedFile)) { using (System.IO.Compression.DeflateStream output = new System.IO.Compression.DeflateStream(destinationFile, System.IO.Compression.CompressionMode.Compress)) { int bytesRead = 0; while (bytesRead < sourceFile.Length) { int ReadLength = sourceFile.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, ReadLength); output.Flush(); bytesRead += ReadLength; } // Whend destinationFile.Flush(); } // End Using System.IO.Compression.GZipStream output destinationFile.Close(); } // End Using System.IO.FileStream destinationFile // Close the files. sourceFile.Close(); } // End Using System.IO.FileStream sourceFile } // End Sub CompressFile
// use the cookiecontainter to retrieve the content of the given url public static string GetWebPageContent(string url, CookieContainer cookieContainer = null) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.MaximumAutomaticRedirections = 4; request.MaximumResponseHeadersLength = 4; request.Method = "GET"; request.Credentials = CredentialCache.DefaultCredentials; request.CookieContainer = cookieContainer; request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); if (response.ContentEncoding.ToLower().Contains("gzip")) responseStream = new System.IO.Compression.GZipStream(responseStream, System.IO.Compression.CompressionMode.Decompress); else if (response.ContentEncoding.ToLower().Contains("deflate")) responseStream = new System.IO.Compression.DeflateStream(responseStream, System.IO.Compression.CompressionMode.Decompress); StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8); string html = readStream.ReadToEnd(); response.Close(); responseStream.Close(); return html; }
public static void SerializableObjectToFile(string path, object obj) { FileStream fs; if (File.Exists(path)) { fs = new FileStream(path, FileMode.Truncate); } else { fs = new FileStream(path, FileMode.Create); } #if UseCompress BinaryFormatter formatter = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); ms.Position = 0; using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress)) { formatter.Serialize(ds, obj); } byte[] buffer = ms.ToArray(); ms.Close(); fs.Write(buffer, 0, buffer.Length); fs.Close(); #else BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, obj); fs.Close(); #endif }
/// <summary> /// Post请求 /// </summary> /// <param name="sUrl">请求的链接</param> /// <param name="PostData">请求的参数</param> /// <returns></returns> public static string HttpPost(string sUrl, string PostData) { byte[] bPostData = System.Text.Encoding.UTF8.GetBytes(PostData); string sResult = string.Empty; HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(sUrl); webRequest.ProtocolVersion = HttpVersion.Version10; webRequest.Timeout = 30000; webRequest.Method = "POST"; webRequest.Headers.Add("Accept-Encoding", "gzip, deflate"); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Headers.Add("Cookie", cookieStr); if (bPostData != null) { Stream postDataStream = webRequest.GetRequestStream(); postDataStream.Write(bPostData, 0, bPostData.Length); } HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse(); if (webResponse.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压 { using (System.IO.Stream streamReceive = webResponse.GetResponseStream()) { using (var zipStream = new System.IO.Compression.GZipStream(streamReceive, System.IO.Compression.CompressionMode.Decompress)) { using (StreamReader sr = new System.IO.StreamReader(zipStream)) { sResult = sr.ReadToEnd(); } } } } else if (webResponse.ContentEncoding.ToLower() == "deflate")//如果使用了deflate则先解压 { using (System.IO.Stream streamReceive = webResponse.GetResponseStream()) { using (var deflateStream = new System.IO.Compression.DeflateStream(streamReceive, System.IO.Compression.CompressionMode.Decompress)) { using (StreamReader sr = new System.IO.StreamReader(deflateStream)) { sResult = sr.ReadToEnd(); } } } } else { using (System.IO.Stream streamReceive = webResponse.GetResponseStream()) { using (System.IO.StreamReader sr = new System.IO.StreamReader(streamReceive)) { sResult = sr.ReadToEnd(); } } } return(sResult); }
/// <summary> /// Decompress using deflate algorithm. /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] Decompress(byte[] data) { byte[] array = null; try { using (MemoryStream inputStream = new MemoryStream(data)) using (MemoryStream outputStream = new MemoryStream()) using (System.IO.Compression.DeflateStream decompressionStream = new System.IO.Compression.DeflateStream(inputStream , System.IO.Compression.CompressionMode.Decompress)) { int count = 2048; byte[] buffer = new byte[count]; for (; ;) { int length = decompressionStream.Read(buffer, 0, count); if (length == 0) { break; } outputStream.Write(buffer, 0, length); } return(outputStream.ToArray()); } } catch (Exception exception) { Energy.Core.Bug.Catch(exception); } return(array); }
/// <summary> /// Сжатие /// </summary> /// <param name="pDataStream"></param> /// <param name="outBufStream"></param> /// <returns></returns> public static bool Deflate(MemoryTributary pDataStream, out MemoryTributary outBufStream) { bool result = true; int DataSize = (int)pDataStream.Length; outBufStream = new MemoryTributary(); pDataStream.Position = 0; try { MemoryTributary srcMemStream = pDataStream; { using (MemoryTributary compressedMemStream = new MemoryTributary()) { using (System.IO.Compression.DeflateStream strmDef = new System.IO.Compression.DeflateStream(compressedMemStream, System.IO.Compression.CompressionMode.Compress)) { srcMemStream.CopyTo(strmDef); } outBufStream = compressedMemStream; } } } catch (Exception ex) { outBufStream = pDataStream; result = false; } return(result); }
private static void _WriteToStream(System.IO.Stream s, ReadOnlySpan <Byte> data, int compression) { if (compression == 1) { using (var ss = new System.IO.Compression.DeflateStream(s, System.IO.Compression.CompressionLevel.Fastest, true)) { _WriteToStream(ss, data, 0); } return; } if (compression == 0) { #if NETSTANDARD2_0 for (int i = 0; i < data.Length; ++i) { s.WriteByte(data[i]); } #else s.Write(data); #endif return; } throw new ArgumentException("invalid compression", nameof(compression)); }
private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { Stream stream = null; StreamReader reader = null; try { // 以字符流的方式读取HTTP响应 stream = rsp.GetResponseStream(); switch (rsp.ContentEncoding) { case "gzip": stream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress); break; case "deflate": stream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress); break; } reader = new StreamReader(stream, encoding); return reader.ReadToEnd(); } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } }
public static byte[] Decompress(byte[] buffer) { // TODO : rename to unity flag #if SCRIPT_ENABLED var decompressBuffer = new List <byte>(); using (var decompressStream = new System.IO.MemoryStream(buffer.Skip(2).Take(buffer.Length - 4).ToArray())) using (var decompressor = new System.IO.Compression.DeflateStream(decompressStream, System.IO.Compression.CompressionMode.Decompress)) { while (true) { byte[] temp = new byte[1024]; int readSize = decompressor.Read(temp, 0, temp.Length); if (readSize == 0) { break; } decompressBuffer.AddRange(temp.Take(readSize)); } } return(decompressBuffer.ToArray()); #else return(null); #endif }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <returns></returns> static string GetResponseContent(WebResponse response) { if (response != null) { var contentEncoding = response.Headers["Content-Encoding"] != null ? response.Headers["Content-Encoding"] : ""; var responseStream = response.GetResponseStream(); switch (contentEncoding) { case "gzip": System.IO.Compression.GZipStream gzipstream = new System.IO.Compression.GZipStream(responseStream, System.IO.Compression.CompressionMode.Decompress); StreamReader gzipreader = new StreamReader(gzipstream); return(gzipreader.ReadToEnd()); case "deflate": System.IO.Compression.DeflateStream deflatestream = new System.IO.Compression.DeflateStream(responseStream, System.IO.Compression.CompressionMode.Decompress); StreamReader deflatereader = new StreamReader(deflatestream); return(deflatereader.ReadToEnd()); default: StreamReader reader = new StreamReader(responseStream); return(reader.ReadToEnd()); } } return(null); }
internal ParticleSystemCompiledShaderData(byte[] shaderCode, bool isXbox, int colourIndex, int userIndex, int lifeIndex) { if (shaderCode == null) throw new ArgumentNullException(); //compress the shader code if (isXbox) { //deflate stream isn't supported shaderCode = Xen.Graphics.ShaderSystem.ShaderSystemBase.SimpleCompress(shaderCode); } else { #if !XBOX360 using (MemoryStream stream = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(shaderCode.Length); using (System.IO.Compression.DeflateStream d = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Compress)) { d.Write(shaderCode, 0, shaderCode.Length); d.Flush(); } shaderCode = stream.ToArray(); } #endif } this.CompressedShaderCode = shaderCode; this.ColourSamplerIndex = colourIndex; this.UserSamplerIndex = userIndex; this.LifeSamplerIndex = lifeIndex; }
public void WillDecodeDeflateResponse() { var testable = new TestableJavaScriptReducer(); var mockWebResponse = new Mock <WebResponse>(); var ms = new MemoryStream(); var stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress); stream.Write(new UTF8Encoding().GetBytes("my response"), 0, "my response".Length); stream.Close(); var encodedArray = ms.ToArray(); ms.Close(); stream.Dispose(); ms.Dispose(); mockWebResponse.Setup(x => x.GetResponseStream()).Returns(new MemoryStream(encodedArray)); mockWebResponse.Setup(x => x.Headers).Returns(new WebHeaderCollection() { { "Content-Encoding", "deflate" } }); testable.Mock <IWebClientWrapper>().Setup(x => x.Download <JavaScriptResource>("http://host/js1.js")).Returns(mockWebResponse.Object); testable.Mock <IMinifier>().Setup(x => x.Minify <JavaScriptResource>("my response;\r\n")).Returns("min"); var result = testable.ClassUnderTest.Process("http://host/js1.js::"); testable.Mock <IStore>().Verify( x => x.Save(Encoding.UTF8.GetBytes("min").MatchEnumerable(), result, "http://host/js1.js::"), Times.Once()); ms.Dispose(); }
public static byte[] ZLibBufferFromStream(System.IO.MemoryStream ms, int offset, int size) { using (var dec = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress, true)) { return(ZLibBufferFromStream(dec, offset, size)); } }
private IEnumerable <VersionDescription> ParseResponse(WebHeaderCollection header, byte[] body) { switch (header.Get("Content-Encoding")) { case "gzip": using (var dst = new System.IO.MemoryStream()) using (var s = new System.IO.Compression.GZipStream(new System.IO.MemoryStream(body), System.IO.Compression.CompressionMode.Decompress)) { s.CopyTo(dst); dst.Flush(); body = dst.ToArray(); } break; case "deflate": using (var dst = new System.IO.MemoryStream()) using (var s = new System.IO.Compression.DeflateStream(new System.IO.MemoryStream(body), System.IO.Compression.CompressionMode.Decompress)) { s.CopyTo(dst); dst.Flush(); body = dst.ToArray(); } break; default: break; } return(ParseAppCast(System.Text.Encoding.UTF8.GetString(body))); }
public static unsafe byte[] Compress(byte[] buffer) { // TODO : rename to unity flag #if SCRIPT_ENABLED using (var compressStream = new System.IO.MemoryStream()) using (var compressor = new System.IO.Compression.DeflateStream(compressStream, System.IO.Compression.CompressionLevel.Optimal)) { UInt32 adder = 0; fixed(byte *b = buffer) { adder = CalcAdler32(b, (UInt32)buffer.Length); } compressor.Write(buffer, 0, buffer.Count()); compressor.Close(); var compressed = compressStream.ToArray(); List <byte[]> dst = new List <byte[]>(); dst.Add(new byte[] { 0x78, 0x9c }); dst.Add(compressed); dst.Add(BitConverter.GetBytes(adder).Reverse().ToArray()); return(dst.SelectMany(_ => _).ToArray()); } #else return(null); #endif }
async Task <bool> ExtractPartAndValidate(PartialZipDownload part, Stream partInputStream, string cacheDirectory) { string fileHash = null; var outputPath = GetOutputPath(cacheDirectory, part); using (var iis = new System.IO.Compression.DeflateStream(partInputStream, System.IO.Compression.CompressionMode.Decompress)) //using (var iis = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream (partInputStream, new ICSharpCode.SharpZipLib.Zip.Compression.Inflater (true))) using (var fs = File.Open(outputPath, FileMode.Create)) { await iis.CopyToAsync(fs).ConfigureAwait(false); await fs.FlushAsync().ConfigureAwait(false); fs.Seek(0, SeekOrigin.Begin); fileHash = DownloadUtils.HashMd5(fs); LogDebugMessage("Hash of Downloaded File: {0}", fileHash); fs.Close(); } if (!string.IsNullOrEmpty(part.Md5) && !part.Md5.Equals(fileHash, StringComparison.InvariantCultureIgnoreCase)) { // TODO: HANDLE LogMessage("File MD5 Hash was invalid, deleting file: {0}", part.ToFile); File.Delete(outputPath); return(false); } return(true); }
/// <summary> /// Recupera o resultado da requisição. /// </summary> /// <param name="response"></param> /// <returns></returns> private RequestResult GetRequestResult(WebResponse response) { if (response != null) { var webResponse = response as HttpWebResponse; var args = new WebClientResponseHeadersReceivedEventArgs(webResponse); OnResponseHeadersReceived(args); var responseStream = new System.IO.MemoryStream(); if (!args.Cancel) { var buffer = new byte[1024]; var read = 0; var contentLength = webResponse.ContentLength; if (string.Compare(webResponse.ContentEncoding, "gzip", true) == 0) { using (var stream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress)) while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { responseStream.Write(buffer, 0, read); OnResponseProgressChanged(contentLength, read); } } else if (string.Compare(webResponse.ContentEncoding, "deflate", true) == 0) { using (var stream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress)) while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { responseStream.Write(buffer, 0, read); OnResponseProgressChanged(contentLength, read); } } else { using (var stream = response.GetResponseStream()) while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { responseStream.Write(buffer, 0, read); OnResponseProgressChanged(contentLength, read); } } responseStream.Seek(0, System.IO.SeekOrigin.Begin); } System.Text.Encoding encoding = null; try { if (webResponse.CharacterSet != null && webResponse.CharacterSet != "") { encoding = System.Text.Encoding.GetEncoding(webResponse.CharacterSet); } } catch { } return(new RequestResult(webResponse, webResponse != null ? webResponse.StatusCode : HttpStatusCode.BadRequest, webResponse != null ? webResponse.StatusDescription : "Bad Request", encoding ?? System.Text.Encoding.Default, responseStream)); } else { return(new RequestResult(null, HttpStatusCode.BadRequest, "Bad Request", System.Text.Encoding.Default, null)); } }
internal Stream GetStream(Stream str) { if (_UseCompression == 2) { // use the built-in compression .NET 2 provides System.IO.Compression.DeflateStream cs = new System.IO.Compression.DeflateStream(str, System.IO.Compression.CompressionMode.Compress); return(cs); } if (_UseCompression == 0) { return(null); } if (_UseCompression == -1) // make sure we're init'ed { Init(); if (_UseCompression != 1) { return(null); } } try { object[] args = new object[] { str }; Stream so = _Assembly.CreateInstance(_ClassName, false, BindingFlags.CreateInstance, null, args, null, null) as Stream; return(so); } catch { return(null); } }
public byte[] decompressFile(CentralDirectoryFileHeader inHeader) { streamPosition = inHeader.fileHeaderOffset; var localHeader = new LocalHeader(); localHeader.load(reader); var compressedBytes = reader.ReadBytes((int)inHeader.compressedSize); if (inHeader.compressionMethod == 0) { return(compressedBytes); } if (inHeader.compressionMethod != 8) //deflate { throw new System.ArgumentException( string.Format("Unsupported compression method {0} in file \"{1}\" of archive \"{2}\"", inHeader.filename, inHeader.compressionMethod, archiveFileName)); } var tmp = new byte[65536]; using (var memStream = new System.IO.MemoryStream(compressedBytes)) using (var deflateStream = new System.IO.Compression.DeflateStream(memStream, System.IO.Compression.CompressionMode.Decompress)) using (var outStream = new System.IO.MemoryStream()){ int bytesRead; while ((bytesRead = deflateStream.Read(tmp, 0, tmp.Length)) > 0) { outStream.Write(tmp, 0, bytesRead); } return(outStream.ToArray()); } }
public override async Task WriteData(ITransport transport, ITransportMetadata metadata, Action <IProtocolWriter> handler) { using (var buffer = new MemoryStream()) { if (this.CompressionEnabled) { using (var compressionStream = new System.IO.Compression.DeflateStream(buffer, System.IO.Compression.CompressionMode.Compress)) { var writer = new BinaryProtocolWriter(compressionStream); handler(writer); } } else { var writer = new BinaryProtocolWriter(buffer); handler(writer); buffer.Position = 0; } var data = buffer.ToArray(); await transport.Send(new TransportMessage(data, VolatileTransportMetadata.FromMetadata(metadata))); } }
public void LoadIndex(Stream fs) { Int64 nIndexPosition = Info.IndexOffset; fs.Seek(nIndexPosition, SeekOrigin.Begin); MountPoint = ReadString(fs); NumEntries = ReadInt32(fs); for (int i = 0; i < NumEntries; i++) { string Filename = ReadString(fs); Console.WriteLine("[" + (i + 1) + " of " + NumEntries + "] " + Filename); PakEntry Entry = new PakEntry(); Entry.DeSerialize(fs); nIndexPosition = fs.Position; if (Entry.bEncrypted != 0) { throw new Exception("Encription not supported!"); } fs.Seek(Entry.Offset, SeekOrigin.Begin); PakEntry FileHeader = new PakEntry(); FileHeader.DeSerialize(fs); if (!System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(Entry.Hash, FileHeader.Hash)) { throw new Exception("Wrong hash!"); } string FilePath = Path.Combine(Program.OutPath, Filename.Replace('/', '\\')); CreatePath(FilePath); Stream fs_out = new FileStream(FilePath, FileMode.Create); if (Entry.CompressionMethod == 0) { byte[] Data = new byte[Entry.Size]; fs.Read(Data, 0, Data.Length); fs_out.Write(Data, 0, Data.Length); } else if (Entry.CompressionMethod == 1) { for (int j = 0; j < Entry.CompressionBlocks.Count; j++) { fs.Seek(Entry.CompressionBlocks[j].CompressedStart + 2, SeekOrigin.Begin); System.IO.Compression.DeflateStream fs_decompressed = new System.IO.Compression.DeflateStream(fs, System.IO.Compression.CompressionMode.Decompress, true); fs_decompressed.CopyTo(fs_out); fs_decompressed.Close(); } } else { throw new Exception("This compression method not supported!"); } fs_out.Close(); fs.Seek(nIndexPosition, SeekOrigin.Begin); } }
} // End Sub Decompress public static byte[] DeflateDecompress(byte[] gzip) { byte[] baRetVal = null; using (System.IO.MemoryStream ByteStream = new System.IO.MemoryStream(gzip)) { // Create a GZIP stream with decompression mode. // ... Then create a buffer and write into while reading from the GZIP stream. using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ByteStream , System.IO.Compression.CompressionMode.Decompress)) { const int size = 4096; byte[] buffer = new byte[size]; using (System.IO.MemoryStream memstrm = new System.IO.MemoryStream()) { int count = 0; count = stream.Read(buffer, 0, size); while (count > 0) { memstrm.Write(buffer, 0, count); memstrm.Flush(); count = stream.Read(buffer, 0, size); } // Whend baRetVal = memstrm.ToArray(); memstrm.Close(); } // End Using memstrm stream.Close(); } // End Using System.IO.Compression.GZipStream stream ByteStream.Close(); } // End Using System.IO.MemoryStream ByteStream return(baRetVal); } // End Sub Decompress
/// <summary> /// Gets the contents of the response. /// </summary> /// <param name="response"></param> /// <returns></returns> public static byte[] GetContent(HttpWebResponse response) { using (var responseStream = response.GetResponseStream()) { var ms = new MemoryStream(); var buffer = new byte[8192]; var bytesRead = 0; int read; Stream s; if (response.ContentEncoding.ToLower().Contains("deflate")) { s = new System.IO.Compression.DeflateStream(responseStream, System.IO.Compression.CompressionMode.Decompress); } else if (response.ContentEncoding.ToLower().Contains("gzip")) { s = new System.IO.Compression.GZipStream(responseStream, System.IO.Compression.CompressionMode.Decompress); } else { s = responseStream; } while ((read = s.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); bytesRead += read; } return(ms.ToArray()); } }
/// <summary> /// this uses the webresponse object to get at the /// stream send back from the server. /// </summary> /// <returns>the error message</returns> protected string ReadResponseString() { if (this.webResponse == null) { return(null); } Stream responseStream = this.webResponse.GetResponseStream(); for (int i = 0; i < this.webResponse.Headers.Count; ++i) { string headerVal = this.webResponse.Headers[i].ToLower(); if (headerVal.Contains("gzip")) { responseStream = new System.IO.Compression.GZipStream(responseStream, System.IO.Compression.CompressionMode.Decompress); break; } if (headerVal.Contains("deflate")) { responseStream = new System.IO.Compression.DeflateStream(responseStream, System.IO.Compression.CompressionMode.Decompress); break; } } if (responseStream == null) { return(null); } StreamReader reader = new StreamReader(responseStream); return(reader.ReadToEnd()); }
public byte[] Write(Action <IProtocolWriter> handler) { using (var buffer = new MemoryStream()) { if (this.Compress) { using (var gzip = new System.IO.Compression.DeflateStream(buffer, System.IO.Compression.CompressionMode.Compress)) { var writer = new EntanglementProtocolWriter(gzip); handler(writer); } } else { var writer = new EntanglementProtocolWriter(buffer); handler(writer); buffer.Position = 0; } var data = buffer.ToArray(); return(data); } }
public Stream GetEntryStream(StiZipEntry entry) { if (_isDisposed) { throw new ObjectDisposedException("ZipFile"); } if (entry.IsCrypted) { throw new StiZipException("Encryption is not supported"); } long start = LocateEntry(entry); CompressionMethod method = entry.CompressionMethod; Stream result = new StiPartialInputStream(this, start, entry.CompressedSize); switch (method) { case CompressionMethod.Stored: break; case CompressionMethod.Deflated: byte[] buf = new byte[entry.CompressedSize]; _baseStream.Seek(start, SeekOrigin.Begin); _baseStream.Read(buf, 0, buf.Length); MemoryStream ms = new MemoryStream(buf); result = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress); break; default: throw new StiZipException("Unsupported compression method " + method); } return(result); }
/// <summary> /// Get请求 /// </summary> /// <param name="sUrl">请求的url</param> /// <returns></returns> public static string HttpGet(string sUrl) { string sResult = string.Empty; try { HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(sUrl); webRequest.ProtocolVersion = HttpVersion.Version10; webRequest.Timeout = 30000; webRequest.Method = WebRequestMethods.Http.Get; webRequest.Headers.Add("Accept-Encoding", "gzip, deflate"); HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse(); if (webResponse.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压 { using (System.IO.Stream streamReceive = webResponse.GetResponseStream()) { using (var zipStream = new System.IO.Compression.GZipStream(streamReceive, System.IO.Compression.CompressionMode.Decompress)) { using (StreamReader sr = new System.IO.StreamReader(zipStream)) { sResult = sr.ReadToEnd(); } } } } else if (webResponse.ContentEncoding.ToLower() == "deflate")//如果使用了deflate则先解压 { using (System.IO.Stream streamReceive = webResponse.GetResponseStream()) { using (var deflateStream = new System.IO.Compression.DeflateStream(streamReceive, System.IO.Compression.CompressionMode.Decompress)) { using (StreamReader sr = new System.IO.StreamReader(deflateStream)) { sResult = sr.ReadToEnd(); } } } } else { using (System.IO.Stream streamReceive = webResponse.GetResponseStream()) { using (System.IO.StreamReader sr = new System.IO.StreamReader(streamReceive)) { sResult = sr.ReadToEnd(); } } } } catch (Exception ex) { logger.Info(ex.Message); logger.Fatal(ex); } logger.Info("请求的Url:" + sUrl); logger.Info("返回的结果:" + sResult); return(sResult); }
/// <summary> /// Compress with Stream /// </summary> public static Stream Compress(Stream input) { System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream( input, System.IO.Compression.CompressionMode.Compress, true); stream.Flush(); return input; }
private static byte[] StreamCompress(byte[] data) { using (var val = new MemoryStream()) { using (var compressor = new System.IO.Compression.DeflateStream(val, System.IO.Compression.CompressionLevel.Optimal)) { return(val.ToArray()); } } }
private static byte[] StreamCompress(byte[] data) { using var val = new MemoryStream(); using (var compressor = new System.IO.Compression.DeflateStream(val, System.IO.Compression.CompressionLevel.Optimal)) { compressor.Write(data, 0, data.Length); } return(val.ToArray()); }
public void ExtractEntry(Entry entry, Stream outputStream, ZipProgressHandler progressHandler = null) { if (entry.Offset >= _Stream.Length) { throw new Exception("Invalid ZIP entry offset"); } _Stream.Seek(entry.Offset, SeekOrigin.Begin); byte[] buffer = new byte[1024 * 1024]; _Stream.Read(buffer, 0, 30); ushort fileNameLength = BitConverter.ToUInt16(buffer, 26); ushort extraFieldLength = BitConverter.ToUInt16(buffer, 28); _Stream.Seek(entry.Offset + 30 + fileNameLength + extraFieldLength, SeekOrigin.Begin); Stream dataStream; switch (entry.CompressionMethod) { case 0: dataStream = _Stream; break; case 8: dataStream = new System.IO.Compression.DeflateStream(_Stream, System.IO.Compression.CompressionMode.Decompress, true); break; default: throw new Exception("Unsupported ZIP compression method: " + entry.CompressionMethod + " for " + entry.FileName); } uint done = 0; while (done < entry.UncompressedSize) { int todo = (int)Math.Min(entry.UncompressedSize - done, (uint)buffer.Length); if (dataStream.Read(buffer, 0, todo) != todo) { throw new Exception("Cannot read data from ZIP stream for " + entry.FileName); } outputStream.Write(buffer, 0, todo); done += (uint)todo; if (progressHandler != null) { progressHandler(done, entry.UncompressedSize); } } if (dataStream != _Stream) { dataStream.Dispose(); } }
private static string GetWebDataFromPost(string url, string postData, CookieContainer cc) { var headers = new NameValueCollection(); headers["Content-type"] = "application/json"; headers.Add("Accept", "*/*"); headers.Add("User-Agent", OnlineVideoSettings.Instance.UserAgent); return(WebCache.Instance.GetWebData(url, postData, cookies: cc, headers: headers)); Log.Debug("get webdata from {0}", url); Log.Debug("postdata = " + postData); // request the data byte[] data = Encoding.UTF8.GetBytes(postData); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; if (request == null) { return(""); } request.Method = "POST"; request.ContentType = "application/json"; request.UserAgent = OnlineVideoSettings.Instance.UserAgent; request.Timeout = 15000; request.ContentLength = data.Length; request.ProtocolVersion = HttpVersion.Version10; request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); request.CookieContainer = cc; Stream requestStream = request.GetRequestStream(); requestStream.Write(data, 0, data.Length); requestStream.Close(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { Stream responseStream; if (response.ContentEncoding.ToLower().Contains("gzip")) { responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress); } else if (response.ContentEncoding.ToLower().Contains("deflate")) { responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress); } else { responseStream = response.GetResponseStream(); } Encoding encoding = Encoding.UTF8; encoding = Encoding.GetEncoding(response.CharacterSet.Trim(new char[] { ' ', '"' })); StreamReader reader = new StreamReader(responseStream, encoding, true); string str = reader.ReadToEnd(); return(str.Trim()); } }
public void Compress() { using (var streamUncompressed = new System.IO.FileStream(@"C:\Users\Adrian\Downloads\2008_civic_sedan.pdf", System.IO.FileMode.Open)) using (var streamCompressed = new System.IO.FileStream(@"C:\Users\Adrian\Downloads\2008_civic_sedan.z", System.IO.FileMode.Create)) { var deflateStream = new System.IO.Compression.DeflateStream(streamCompressed, System.IO.Compression.CompressionMode.Compress); streamUncompressed.CopyTo(deflateStream); } }
/// <summary> /// Gets the response stream with HTTP decompression. /// </summary> /// <param name="response">The response.</param> /// <returns></returns> public static Stream GetResponseStreamWithHttpDecompression(this WebResponse response) { var stream = response.GetResponseStream(); var encoding = response.Headers["Content-Encoding"]; if (encoding != null && encoding.Contains("gzip")) stream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress); else if (encoding != null && encoding.Contains("deflate")) stream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress); return stream; }
/// <summary> /// Gets the response stream with HTTP decompression. /// </summary> /// <param name="response">The response.</param> /// <returns></returns> public static Stream GetResponseStreamWithHttpDecompression(this HttpResponseMessage response) { var stream = response.Content.ReadAsStreamAsync().Result; var encoding = response.Headers.GetValues("Content-Encoding"); if (encoding != null && encoding.Contains("gzip")) stream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress); else if (encoding != null && encoding.Contains("deflate")) stream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress); return stream; }
/// <summary> /// Initializes a new instance of the <see cref="ZlibStream"/> class by using the specified stream and compression level, and optionally leaves the stream open. /// </summary> /// <param name="stream">The stream to compress or decompress.</param> /// <param name="compressionLevel">One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing the stream.</param> /// <param name="leaveOpen">true to leave the stream open after disposing the <see cref="ZlibStream"/> object; otherwise, false.</param> public ZlibStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) { #if !PORTABLE _stream = stream; _leaveOpen = leaveOpen; _deflateStream = new DeflateStream(stream, compressionLevel.ToCompressionLevel(), true); WriteHeader(); #endif }
public void Run() { try { while (_running) { string xml = @"<?xml version=""1.0"" ?> <methodResponse> <params> <param> <value>Alabama</value> </param> </params> </methodResponse>"; HttpListenerContext context = _lstner.GetContext(); switch (encoding) { case "gzip": context.Response.Headers.Add("Content-Encoding", "gzip"); break; case "deflate": context.Response.Headers.Add("Content-Encoding", "deflate"); break; default: break; } context.Response.ContentEncoding = System.Text.Encoding.UTF32; Stream respStm = context.Response.OutputStream; Stream compStm; switch (encoding) { case "gzip": compStm = new System.IO.Compression.GZipStream(respStm, System.IO.Compression.CompressionMode.Compress); break; case "deflate": compStm = new System.IO.Compression.DeflateStream(respStm, System.IO.Compression.CompressionMode.Compress); break; default: compStm = null; break; } StreamWriter wrtr = new StreamWriter(compStm); wrtr.Write(xml); wrtr.Close(); } } catch (HttpListenerException ex) { } }
public Exception Download(DownloadInfo downloadInfo) { HttpWebResponse response = null; try { downloadThread = System.Threading.Thread.CurrentThread; using (FileStream fs = new FileStream(downloadInfo.LocalFile, FileMode.Create, FileAccess.Write, FileShare.None)) { HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(downloadInfo.Url); request.Timeout = 15000; request.UserAgent = OnlineVideoSettings.Instance.UserAgent; request.Accept = "*/*"; request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); response = (HttpWebResponse)request.GetResponse(); Stream responseStream; if (response.ContentEncoding.ToLower().Contains("gzip")) responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress); else if (response.ContentEncoding.ToLower().Contains("deflate")) responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress); else responseStream = response.GetResponseStream(); long size = response.ContentLength; int buffSize = 4096; byte[] buffer = new byte[buffSize]; long totalRead = 0; long readSize; do { readSize = responseStream.Read(buffer, 0, buffSize); totalRead += readSize; fs.Write(buffer, 0, (int)readSize); downloadInfo.DownloadProgressCallback(size, totalRead); } while (readSize > 0 && !Cancelled); fs.Flush(); fs.Close(); return null; } } catch (Exception ex) { return ex; } finally { if (response != null) response.Close(); } }
string Decode(Stream s) { // skip first two bytes //Console.WriteLine(s.Length); //s.ReadByte(); //s.ReadByte(); using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(s, System.IO.Compression.CompressionMode.Decompress)) { //ds.Flush(); //byte[] b = new byte[100]; // int a = ds.Read(b, 0, 100); //Console.WriteLine(a); return new StreamReader(ds).ReadToEnd(); //Console.WriteLine(r); } }
static void Decode(Stream s) { // skip first two bytes Console.WriteLine(s.Length); s.ReadByte(); s.ReadByte(); using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(s, System.IO.Compression.CompressionMode.Decompress)) { ds.Flush(); byte []b = new byte[100]; int a = ds.Read(b, 0, 100); Console.WriteLine(a); string r = new StreamReader(ds).ReadToEnd(); Console.WriteLine(r); } }
public static string Decompress(string strSource, int length) { byte[] buffer = Convert.FromBase64String(strSource); System.IO.MemoryStream ms = new System.IO.MemoryStream(); ms.Write(buffer, 0, buffer.Length); ms.Position = 0; System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress); stream.Flush(); int nSize = length; byte[] decompressBuffer = new byte[nSize]; int nSizeIncept = stream.Read(decompressBuffer, 0, nSize); stream.Close(); return System.Text.Encoding.Unicode.GetString(decompressBuffer, 0, nSizeIncept);//转换为普通的字符串 }
public static byte[] Unzip(byte[] data) { System.IO.Compression.CompressionMode mode = System.IO.Compression.CompressionMode.Decompress; System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream( new System.IO.MemoryStream(data), mode); System.IO.MemoryStream mem = new System.IO.MemoryStream(); byte[] buffer = new byte[4096]; while (true) { int count = stream.Read(buffer, 0, buffer.Length); if (count != 0) mem.Write(buffer, 0, count); if (count != buffer.Length) break; } stream.Close(); return mem.ToArray(); }
public static string Compress(string strSource) { if (strSource == null) throw new System.ArgumentException("字符串为空!"); System.Text.Encoding encoding = System.Text.Encoding.Unicode; byte[] buffer = encoding.GetBytes(strSource); 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 buffer; return Convert.ToBase64String(buffer); //将压缩后的byte[]转换为Base64String }
/// <summary> /// Returns a MemoryStream with the 'inflated' contents of the file specified in the <paramref name="path"/> parameter. /// </summary> /// <param name="path">Full path to the deflated file</param> /// <returns>Decompressed (inflated) MemoryStream</returns> public static MemoryStream Decompress(string path) { byte[] buffer = new byte[bufferLength]; int size; MemoryStream output = new MemoryStream(); using (FileStream fs = new FileStream(path, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read, 8192)) { // MS, dare to be different ;-) // Skip the first two bytes, see : http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97064 fs.ReadByte(); fs.ReadByte(); using (System.IO.Compression.DeflateStream inflaterStream = new System.IO.Compression.DeflateStream(fs, System.IO.Compression.CompressionMode.Decompress, false)) { while ((size = inflaterStream.Read(buffer, 0, buffer.Length)) > 0) output.Write(buffer, 0, size); } } return output; }
public static object DecompressAndDecode(byte[] input) { MemoryStream compressedStream = new MemoryStream(input); compressedStream.Seek(2, SeekOrigin.Begin); //skip zlib header, we're only interested in the deflated bytes byte[] outputBytes = new byte[4096]; DeflateStream stream = new DeflateStream(compressedStream, CompressionMode.Decompress); try { stream.Read(outputBytes, 0, (int) input.Length); stream.Flush(); stream.Close(); return Rencode.Decode(outputBytes); } catch (Exception e) { //Console.WriteLine("Exception reading stream"); } return null; }
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); AssemblyName assemblyName = new AssemblyName(args.Name); string path = assemblyName.Name + ".gzip"; if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false) { path = String.Format(@"{0}\{1}", assemblyName.CultureInfo, path); } using (Stream stream = executingAssembly.GetManifestResourceStream(path)) { if (stream == null) return null; using (var dll = new MemoryStream()) using (var inflate = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress)) { inflate.CopyTo(dll); return Assembly.Load(dll.ToArray()); } } }
/// <summary> /// Returns a byte-array with the 'inflated' contents of the input array. /// </summary> /// <param name="input">inflated byte-array</param> /// <returns>Decompressed (inflated) byte-array</returns> public static byte[] Decompress(byte[] input) { byte[] buffer = new byte[1024]; int size; using (MemoryStream outputStream = new MemoryStream()) { using (MemoryStream inputStream = new MemoryStream(input)) { // MS, dare to be different ;-) // Skip the first two bytes, see : http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97064 inputStream.ReadByte(); inputStream.ReadByte(); using (System.IO.Compression.DeflateStream inflaterStream = new System.IO.Compression.DeflateStream(inputStream, System.IO.Compression.CompressionMode.Decompress, false)) { while ((size = inflaterStream.Read(buffer, 0, buffer.Length)) > 0) outputStream.Write(buffer, 0, size); } } return outputStream.ToArray(); } }
// Convert an object to a byte array public static byte[] ToBytes(object obj) { if(obj == null) return new byte[1] { 0 }; if (obj is string) { if (((string)obj) == "") return new byte[1] { 4 }; var buf = System.Text.Encoding.UTF8.GetBytes((string)obj); using (var ms = new MemoryStream()) { using (var zs = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { zs.Write(buf, 0, buf.Length); } if (ms.Length < buf.Length) return ms.ToArray().Prepend((byte)2).ToArray(); else return buf.Prepend((byte)3).ToArray(); } } else { using (var ms = new MemoryStream()) { ms.Write(new byte[1] { 1 }, 0, 1); using (var zs = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { var f = new BinaryFormatter(); f.Serialize(zs, obj); } return ms.ToArray(); } } }
// support for gzip and deflate /// <summary> /// /// </summary> /// <param name="httpWebResp"></param> /// <param name="respStream"></param> /// <returns></returns> protected Stream MaybeDecompressStream(HttpWebResponse httpWebResp, Stream respStream) { Stream decodedStream; string contentEncoding = httpWebResp.ContentEncoding.ToLower(); string coen = httpWebResp.Headers["Content-Encoding"]; if (contentEncoding.Contains("gzip")) { decodedStream = new System.IO.Compression.GZipStream(respStream, System.IO.Compression.CompressionMode.Decompress); } else if (contentEncoding.Contains("deflate")) { decodedStream = new System.IO.Compression.DeflateStream(respStream, System.IO.Compression.CompressionMode.Decompress); } else decodedStream = respStream; return decodedStream; }
short[,] DecompressImageData(byte[] data, int width, int height) { // Decompress with deflate, then remove filter short[,] pixels = new short[height, width]; using (MemoryStream imageData = new MemoryStream()) { using (MemoryStream ms = new MemoryStream(data)) { // skip 2 bytes for zlib specs ms.ReadByte(); ms.ReadByte(); using (System.IO.Compression.DeflateStream deflate = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress, false)) { deflate.CopyTo(imageData); } } // Remove Filter imageData.Seek(0, SeekOrigin.Begin); for (int i = 0; i < height; ++i) { // beginning of scanline, there's one byte of filter type byte filterType = (byte)imageData.ReadByte(); for (int j = 0; j < width; ++j) { // within the scanline, each pixel is 2 bytes byte hiX = (byte)imageData.ReadByte(); byte loX = (byte)imageData.ReadByte(); byte hiA = 0; byte loA = 0; byte hiB = 0; byte loB = 0; byte hiC = 0; byte loC = 0; if (j > 0) { // A = previous pixel hiA = (byte)(pixels[i, j - 1] >> 8); loA = (byte)(pixels[i, j - 1] & 0xFF); } // B = pixel above scanline if (i > 0) { hiB = (byte)(pixels[i - 1, j] >> 8); loB = (byte)(pixels[i - 1, j] & 0xFF); } if (i > 0 && j > 0) { // C previous pixel above scanline hiC = (byte)(pixels[i - 1, j - 1] >> 8); loC = (byte)(pixels[i - 1, j - 1] & 0xFF); } pixels[i, j] = (short)(ReconstructFilteredByte(filterType, hiX, hiA, hiB, hiC) << 8 | ReconstructFilteredByte(filterType, loX, loA, loB, loC)); } } } return pixels; }
/// <summary> /// Compress given data using compressor named in contentEncoding. Set the response header accordingly. /// </summary> /// <param name="data">PhpBytes or string to be compressed.</param> /// <param name="httpcontext">Current HttpContext.</param> /// <param name="contentEncoding">gzip or deflate</param> /// <returns>Byte stream of compressed data.</returns> private static PhpBytes DoGzipHandler(object data, HttpContext/*!*/httpcontext, ContentEncoding contentEncoding) { PhpBytes phpbytes = data as PhpBytes; var inputbytes = (phpbytes != null) ? phpbytes.ReadonlyData : Configuration.Application.Globalization.PageEncoding.GetBytes(PHP.Core.Convert.ObjectToString(data)); using (var outputStream = new System.IO.MemoryStream()) { System.IO.Stream compressionStream; switch (contentEncoding) { case ContentEncoding.gzip: compressionStream = new System.IO.Compression.GZipStream(outputStream, System.IO.Compression.CompressionMode.Compress); break; case ContentEncoding.deflate: compressionStream = new System.IO.Compression.DeflateStream(outputStream, System.IO.Compression.CompressionMode.Compress); break; default: throw new ArgumentException("Not recognized content encoding to be compressed to.", "contentEncoding"); } using (compressionStream) { compressionStream.Write(inputbytes, 0, inputbytes.Length); } //Debug.Assert( // ScriptContext.CurrentContext.Headers["content-encoding"] != contentEncoding, // "The content encoding was already set to '" + contentEncoding + "'. The ob_gzhandler() was called subsequently probably."); ScriptContext.CurrentContext.Headers["content-encoding"] = contentEncoding.ToString(); return new PhpBytes(outputStream.ToArray()); } }
internal Stream GetStream(Stream str) { if (_UseCompression == 2) { // use the built-in compression .NET 2 provides System.IO.Compression.DeflateStream cs = new System.IO.Compression.DeflateStream(str, System.IO.Compression.CompressionMode.Compress); return cs; } if (_UseCompression == 0) return null; if (_UseCompression == -1) // make sure we're init'ed { Init(); if (_UseCompression != 1) return null; } try { object[] args = new object[] {str}; Stream so = _Assembly.CreateInstance(_ClassName, false, BindingFlags.CreateInstance, null, args, null,null) as Stream; return so; } catch { return null; } }
/// <summary> /// this uses the webresponse object to get at the /// stream send back from the server. /// </summary> /// <returns>the error message</returns> protected string ReadResponseString() { if (this.webResponse == null) return (null); Stream responseStream = this.webResponse.GetResponseStream(); for (int i = 0; i < this.webResponse.Headers.Count; ++i) { string headerVal = this.webResponse.Headers[i].ToLower(); if (headerVal.Contains("gzip")) { responseStream = new System.IO.Compression.GZipStream(responseStream, System.IO.Compression.CompressionMode.Decompress); break; } if (headerVal.Contains("deflate")) { responseStream = new System.IO.Compression.DeflateStream(responseStream, System.IO.Compression.CompressionMode.Decompress); break; } } if (responseStream == null) return (null); StreamReader reader = new StreamReader(responseStream); return (reader.ReadToEnd()); }
// thank you: http://www.dotnetperls.com/decompress public static byte[] DecompressBytes(byte[] gzip) { try { byte[] result; using (MemoryStream ms = new MemoryStream()) { ms.Write(gzip, 0, gzip.Length); ms.Position = 0L; using (System.IO.Compression.GZipStream stream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress, true)) { result = ToByteArray(stream); } } if (result == null) throw new Exception("Result was null in GZip decompress."); return result; } catch (InvalidDataException /* ex */) { //Utils.Logger(ex.GetType().ToString() + ": " + ex.Message); return gzip; } catch // (Exception ex) { //Utils.Logger(ex.GetType().ToString() + ": " + ex.Message); try { using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(new MemoryStream(gzip), System.IO.Compression.CompressionMode.Decompress)) { const int size = 4096; byte[] buffer = new byte[size]; using (MemoryStream memory = new MemoryStream()) { int count = 0; do { count = stream.Read(buffer, 0, size); if (count > 0) memory.Write(buffer, 0, count); } while (count > 0); return memory.ToArray(); } } } catch { return gzip; } } }
public static byte[] Zip(byte[] data) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.Compression.DeflateStream zStream = new System.IO.Compression.DeflateStream( stream, System.IO.Compression.CompressionMode.Compress, true); zStream.Write(data, 0, data.Length); zStream.Close(); return stream.ToArray(); }
/// <summary> /// Writes blob and it's header to the underlaying stream. /// </summary> /// <param name="blobType">The type of the blob.</param> /// <param name="blobContent">The pbf serialized content of the blob.</param> private void WriteBlob(string blobType, byte[] blobContent) { Blob blob = new Blob(); if (this.Settings.Compression == CompressionMode.None) { blob.Raw = blobContent; } else if (this.Settings.Compression == CompressionMode.ZlibDeflate) { MemoryStream zlibStream = new MemoryStream(); //ZLIB header zlibStream.WriteByte(120); zlibStream.WriteByte(156); using (System.IO.Compression.DeflateStream deflateSteram = new System.IO.Compression.DeflateStream(zlibStream, System.IO.Compression.CompressionMode.Compress, true)) { deflateSteram.Write(blobContent, 0, blobContent.Length); } blob.RawSize = (int)blobContent.Length; blob.ZlibData = new byte[zlibStream.Length]; Array.Copy(zlibStream.GetBuffer(), blob.ZlibData, zlibStream.Length); } MemoryStream blobStream = new MemoryStream(); Serializer.Serialize<Blob>(blobStream, blob); BlobHeader header = new BlobHeader(); header.Type = blobType; header.DataSize = (int)blobStream.Length; Serializer.SerializeWithLengthPrefix(_output, header, PrefixStyle.Fixed32BigEndian); blobStream.WriteTo(_output); }
protected virtual void ApiAsync(HttpMethod httpMethod, string path, object parameters, Type resultType, object userState) { Stream input; bool containsEtag; IList<int> batchEtags = null; var httpHelper = PrepareRequest(httpMethod, path, parameters, resultType, out input, out containsEtag, out batchEtags); _httpWebRequest = httpHelper.HttpWebRequest; #if FLUENTHTTP_CORE_TPL if (HttpWebRequestWrapperCreated != null) HttpWebRequestWrapperCreated(this, new HttpWebRequestCreatedEventArgs(userState, httpHelper.HttpWebRequest)); #endif var uploadProgressChanged = UploadProgressChanged; bool notifyUploadProgressChanged = uploadProgressChanged != null && httpHelper.HttpWebRequest.Method == "POST"; httpHelper.OpenReadCompleted += (o, e) => { FuntownApiEventArgs args; if (e.Cancelled) { args = new FuntownApiEventArgs(e.Error, true, userState, null); } else if (e.Error == null) { string responseString = null; try { using (var stream = e.Result) { #if NETFX_CORE bool compressed = false; var contentEncoding = httpHelper.HttpWebResponse.Headers.AllKeys.Contains("Content-Encoding") ? httpHelper.HttpWebResponse.Headers["Content-Encoding"] : null; if (contentEncoding != null) { if (contentEncoding.IndexOf("gzip") != -1) { using (var uncompressedStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var reader = new StreamReader(uncompressedStream)) { responseString = reader.ReadToEnd(); } } compressed = true; } else if (contentEncoding.IndexOf("deflate") != -1) { using (var uncompressedStream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var reader = new StreamReader(uncompressedStream)) { responseString = reader.ReadToEnd(); } } compressed = true; } } if (!compressed) { using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } } #else var response = httpHelper.HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) headers[headerName] = response.Headers[headerName]; jsonObject["headers"] = headers; args = new FuntownApiEventArgs(null, false, userState, jsonObject); OnCompleted(httpMethod, args); return; } using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } #endif } try { object result = ProcessResponse(httpHelper, responseString, resultType, containsEtag, batchEtags); args = new FuntownApiEventArgs(null, false, userState, result); } catch (Exception ex) { args = new FuntownApiEventArgs(ex, false, userState, null); } } catch (Exception ex) { args = httpHelper.HttpWebRequest.IsCancelled ? new FuntownApiEventArgs(ex, true, userState, null) : new FuntownApiEventArgs(ex, false, userState, null); } } else { var webEx = e.Error as WebExceptionWrapper; if (webEx == null) { args = new FuntownApiEventArgs(e.Error, httpHelper.HttpWebRequest.IsCancelled, userState, null); } else { if (webEx.GetResponse() == null) { args = new FuntownApiEventArgs(webEx, false, userState, null); } else { var response = httpHelper.HttpWebResponse; if (response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) headers[headerName] = response.Headers[headerName]; jsonObject["headers"] = headers; args = new FuntownApiEventArgs(null, false, userState, jsonObject); } else { httpHelper.OpenReadAsync(); return; } } } } OnCompleted(httpMethod, args); }; if (input == null) { httpHelper.OpenReadAsync(); } else { // we have a request body so write httpHelper.OpenWriteCompleted += (o, e) => { FuntownApiEventArgs args; if (e.Cancelled) { input.Dispose(); args = new FuntownApiEventArgs(e.Error, true, userState, null); } else if (e.Error == null) { try { using (var stream = e.Result) { // write input to requestStream var buffer = new byte[BufferSize]; int nread; if (notifyUploadProgressChanged) { long totalBytesToSend = input.Length; long bytesSent = 0; while ((nread = input.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, nread); stream.Flush(); // notify upload progress changed bytesSent += nread; OnUploadProgressChanged(new FuntownUploadProgressChangedEventArgs(0, 0, bytesSent, totalBytesToSend, ((int)(bytesSent * 100 / totalBytesToSend)), userState)); } } else { while ((nread = input.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, nread); stream.Flush(); } } } httpHelper.OpenReadAsync(); return; } catch (Exception ex) { args = new FuntownApiEventArgs(ex, httpHelper.HttpWebRequest.IsCancelled, userState, null); } finally { input.Dispose(); } } else { input.Dispose(); var webExceptionWrapper = e.Error as WebExceptionWrapper; if (webExceptionWrapper != null) { var ex = webExceptionWrapper; if (ex.GetResponse() != null) { httpHelper.OpenReadAsync(); return; } } args = new FuntownApiEventArgs(e.Error, false, userState, null); } OnCompleted(httpMethod, args); }; httpHelper.OpenWriteAsync(); } }
public unsafe void CreateTexture(BinaryReader reader, int[] palette) { if (Width == 0 || Height == 0) return; Image = new Bitmap(Width, Height); MaskImage = new Bitmap(1, 1); BitmapData data = Image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); byte[] bytes = new byte[0]; byte[] maskbytes = new byte[0]; MemoryStream output; switch (nType) { case 0://wemade wil file uncompressed if (palette.Length > 256) { bo16bit = true; nSize = nSize * 2; } bytes = reader.ReadBytes(nSize); break; case 1://shanda wzl file compressed case 4://shanda miz file compressed output = new MemoryStream(); Ionic.Zlib.ZlibStream deflateStream = new Ionic.Zlib.ZlibStream(output,Ionic.Zlib.CompressionMode.Decompress); deflateStream.Write(reader.ReadBytes(nSize), 0, nSize); bytes = output.ToArray(); deflateStream.Close(); output.Close(); break; case 2: byte Compressed = reader.ReadByte(); reader.ReadBytes(5); if (Compressed != 8) { bytes = reader.ReadBytes(nSize - 6); break; } MemoryStream input = new MemoryStream(reader.ReadBytes(nSize-6)); output = new MemoryStream(); byte[] buffer = new byte[10]; System.IO.Compression.DeflateStream decompress = new System.IO.Compression.DeflateStream(input, System.IO.Compression.CompressionMode.Decompress); int len; while ((len = decompress.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } bytes = output.ToArray(); decompress.Close(); output.Close(); input.Close(); break; case 3: MaskImage = new Bitmap(Width, Height); byte[][] DecodedPixels = DecompressWemadeMir3(reader,Width,Height,nSize); if (DecodedPixels != null) { bytes = DecodedPixels[0]; if (HasMask) maskbytes = DecodedPixels[1]; } else { HasMask = false; bytes = new byte[Width * Height * 2]; } break; } int index = 0; int* scan0 = (int*) data.Scan0; { for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) { if (bo16bit) scan0[y * Width + x] = convert16bitTo32bit(bytes[index++] + (bytes[index++] << 8)); else scan0[y*Width + x] = palette[bytes[index++]]; } if (((nType == 1) || (nType == 4)) & (Width % 4 > 0)) index += WidthBytes(bo16bit ? 16 : 8, Width) - (Width * (bo16bit ? 2 : 1)); } } Image.UnlockBits(data); index = 0; if (HasMask) { BitmapData Maskdata = MaskImage.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* maskscan0 = (int*)Maskdata.Scan0; { for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) maskscan0[y * Width + x] = convert16bitTo32bit(maskbytes[index++] + (maskbytes[index++] << 8)); } } MaskImage.UnlockBits(Maskdata); } }
public static MemoryStream DecompressDeflate(Stream thestream) { MemoryStream ms = new MemoryStream(); using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(thestream, System.IO.Compression.CompressionMode.Decompress,true)) { byte[] buffer = new byte[8192]; int bytesread = ds.Read(buffer, 0, buffer.Length); while (bytesread != 0) { ms.Write(buffer, 0, bytesread); bytesread = ds.Read(buffer, 0, buffer.Length); } ms.Position = 0; } return ms; }