public static string GZIPdecompress(byte[] to_decompress) { Stream stream = new MemoryStream(to_decompress); MemoryStream outBuffer = new MemoryStream(); try { System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress); byte[] buf = new byte[512]; while (true) { int bytesRead = gzip.Read(buf, 0, buf.Length); if (bytesRead <= 0) { break; } else { outBuffer.Write(buf, 0, bytesRead); } } gzip.Close(); } catch { } return(Encoding.UTF8.GetString(outBuffer.ToArray())); }
/// <summary> /// Gzip格式解压缩 /// </summary> /// <param name="value"></param> /// <returns></returns> public static byte[] UnZip(byte[] byteArray) { //Prepare for decompress System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray); System.IO.Compression.GZipStream gZip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); //Reset variable to collect uncompressed result MemoryStream source = new MemoryStream(); //从压缩流中读出所有数据 byte[] tmpByteArray = new byte[1024]; int n; while ((n = gZip.Read(tmpByteArray, 0, tmpByteArray.Length)) != 0) { source.Write(tmpByteArray, 0, n); } gZip.Close(); ms.Close(); gZip.Dispose(); ms.Dispose(); return(source.ToArray()); }
public static HistSimIndex FromFile(string filepath, DebugDelegate debug) { try { HistSimIndex hsi; // prepare serializer XmlSerializer xs = new XmlSerializer(typeof(HistSimIndex)); // read in message Stream fs = new FileStream(filepath, FileMode.Open); // uncompress System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Decompress); // deserialize message hsi = (HistSimIndex)xs.Deserialize(gs); // close everything gs.Close(); // close serializer fs.Close(); // unpack toc hsi.unpackTOC(); return(hsi); } catch (Exception ex) { if (debug != null) { debug(ex.Message + ex.StackTrace); } return(null); } }
/// <summary> /// 字符串解压缩 /// </summary> /// <param name="strSource"></param> /// <returns></returns> public static byte[] Decompress(byte[] data) { try { System.IO.MemoryStream ms = new System.IO.MemoryStream(data); System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress, true); System.IO.MemoryStream msreader = new System.IO.MemoryStream(); byte[] buffer = new byte[0x1000]; while (true) { int reader = zip.Read(buffer, 0, buffer.Length); if (reader <= 0) { break; } msreader.Write(buffer, 0, reader); } zip.Close(); ms.Close(); msreader.Position = 0; buffer = msreader.ToArray(); msreader.Close(); return(buffer); } catch (Exception e) { throw new Exception(e.Message); } }
public static string UnZip(string value) { byte[] array = new byte[value.Length]; int num = 0; char[] array2 = value.ToCharArray(); for (int i = 0; i < array2.Length; i++) { char c = array2[i]; array[num++] = (byte)c; } MemoryStream memoryStream = new MemoryStream(array); System.IO.Compression.GZipStream gZipStream = new System.IO.Compression.GZipStream(memoryStream, System.IO.Compression.CompressionMode.Decompress); array = new byte[array.Length]; int num2 = gZipStream.Read(array, 0, array.Length); StringBuilder stringBuilder = new StringBuilder(num2); for (int j = 0; j < num2; j++) { stringBuilder.Append((char)array[j]); } gZipStream.Close(); memoryStream.Close(); gZipStream.Dispose(); memoryStream.Dispose(); return(stringBuilder.ToString()); }
public void WillDecodeGZipedResponse() { var testable = new TestableJavaScriptReducer(); var mockWebResponse = new Mock <WebResponse>(); var ms = new MemoryStream(); var stream = new System.IO.Compression.GZipStream(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", "gzip" } }); 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(); }
} // End Sub DeCompressFile // http://www.dotnetperls.com/decompress public static byte[] Decompress(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.GZipStream stream = new System.IO.Compression.GZipStream(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
public static string lerror = ""; // Gets the last error that occurred in this struct. Similar to the C perror(). public static bool Decompress(byte[] indata, string outfile) { try { System.IO.MemoryStream ms = new System.IO.MemoryStream(indata); System.IO.StreamWriter sw = new System.IO.StreamWriter(outfile); System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); int lbyte = gzs.ReadByte(); while (lbyte != -1) { sw.BaseStream.WriteByte((byte)lbyte); lbyte = gzs.ReadByte(); } gzs.Close(); gzs.Dispose(); sw.Close(); sw.Dispose(); } catch (System.Exception ex) { lerror = ex.Message; return(false); } return(true); }
public string Zip(string value) { //Transform string into byte[] byte[] byteArray = this.StrToByteArray(value); //Prepare for compress System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream( ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string // C# to convert a byte array to a string. byteArray = ms.ToArray(); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); string str = enc.GetString(byteArray); ms.Close(); sw.Dispose(); ms.Dispose(); return(str); }
public static string ZipCompress(this string value) { //Transform string into byte[] byte[] byteArray = new byte[value.Length]; int indexBA = 0; foreach (char item in value.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for compress System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string byteArray = ms.ToArray(); System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length); foreach (byte item in byteArray) { sB.Append((char)item); } ms.Close(); sw.Dispose(); ms.Dispose(); return sB.ToString(); }
public string UnZip(string value) { //Transform string into byte[] byte[] byteArray = this.StrToByteArray(value); //Prepare for decompress System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray); System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); //Reset variable to collect uncompressed result byteArray = new byte[byteArray.Length]; //Decompress int rByte = sr.Read(byteArray, 0, byteArray.Length); //Transform byte[] unzip data to string System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); string str = enc.GetString(byteArray); sr.Close(); ms.Close(); sr.Dispose(); ms.Dispose(); return(str); }
public string UnZip(string value) { //Transform string into byte[] byte[] byteArray = new byte[value.Length]; int indexBA = 0; foreach (char item in value.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for decompress System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray); System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); //Reset variable to collect uncompressed result byteArray = new byte[byteArray.Length]; //Decompress int rByte = sr.Read(byteArray, 0, byteArray.Length); //Transform byte[] unzip data to string System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte); //Read the number of bytes GZipStream red and do not a for each bytes in //resultByteArray; for (int i = 0; i < rByte; i++) { sB.Append((char)byteArray[i]); } sr.Close(); ms.Close(); sr.Dispose(); ms.Dispose(); return(sB.ToString()); }
/// <summary> /// In Memory GZip Decompressor /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] GZip_Decompress(this byte[] data) { int length = 100000; //10Kb byte[] Ob = new byte[length]; byte[] result = null; using (var ms = new MemoryStream(data)) { using (var gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)) { int a = 0; while ((a = gz.Read(Ob, 0, length)) > 0) { if (a == length) { result = result.Concat(Ob); } else { result = result.Concat(Ob.Substring(0, a)); } } gz.Close(); } ms.Close(); } return(result); }
static byte[] UnGzip(byte[] buffer) { if (buffer[0] == 31 && buffer[1] == 139) { MemoryStream msIn = new MemoryStream(buffer); MemoryStream msOut = new MemoryStream(); System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(msIn, System.IO.Compression.CompressionMode.Decompress); byte[] data = new byte[2048]; while (true) { int count = gzip.Read(data, 0, 2048); msOut.Write(data, 0, count); if (count < 2048) { break; } } gzip.Close(); msOut.Close(); return(msOut.ToArray()); } return(buffer); }
public static string UnZip(string value) { //Transform string into byte[] byte[] byteArray = new byte[value.Length]; int indexBA = 0; foreach (char item in value.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for decompress System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray); System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); //Reset variable to collect uncompressed result byteArray = new byte[byteArray.Length]; //Decompress int rByte = sr.Read(byteArray, 0, byteArray.Length); //Transform byte[] unzip data to string System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte); //Read the number of bytes GZipStream red and do not a for each bytes in //resultByteArray; for (int i = 0; i < rByte; i++) { sB.Append((char)byteArray[i]); } sr.Close(); ms.Close(); sr.Dispose(); ms.Dispose(); return sB.ToString(); }
public static string Zip(string value) { //Transform string into byte[] byte[] byteArray = new byte[value.Length]; int indexBA = 0; foreach (char item in value.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for compress System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string byteArray = ms.ToArray(); System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length); foreach (byte item in byteArray) { sB.Append((char)item); } ms.Close(); sw.Dispose(); ms.Dispose(); return(sB.ToString()); }
/// <summary> /// In Memory GZip Decompressor /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] GZip_Decompress(this byte[] data) { int length = 100000; //10Kb byte[] Ob = new byte[length]; byte[] result = null; using (var ms = new MemoryStream(data)) { using (var gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)) { int a = 0; while ((a = gz.Read(Ob, 0, length)) > 0) { if (a == length) result = result.Concat(Ob); else result = result.Concat(Ob.Substring(0, a)); } gz.Close(); } ms.Close(); } return result; }
/// <summary> /// Компрессия или декомпрессия файла /// </summary> /// <param name="fromFile">Исходный файл для компрессии или декомпрессии</param> /// <param name="toFile">Целевой файл</param> /// <param name="compressionMode">Указывает на компрессию или декомпрессию</param> private static void CompressOrDecompressFile(string fromFile, string toFile, System.IO.Compression.CompressionMode compressionMode) { System.IO.FileStream toFs = null; System.IO.Compression.GZipStream gzStream = null; System.IO.FileStream fromFs = new System.IO.FileStream(fromFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); try { toFs = new System.IO.FileStream(toFile, System.IO.FileMode.Create, System.IO.FileAccess.Write); gzStream = new System.IO.Compression.GZipStream(toFs, compressionMode); byte[] buf = new byte[fromFs.Length]; fromFs.Read(buf, 0, buf.Length); gzStream.Write(buf, 0, buf.Length); } finally { if (gzStream != null) gzStream.Close(); if (toFs != null) toFs.Close(); fromFs.Close(); } }
public void Close() { LinePtr.Close(); if (UnGZPtr is object) { UnGZPtr.Close(); } }
/// <summary> /// This function return a byte array compressed by GZIP algorithm. /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] CompressGZIP(byte[] data) { System.IO.MemoryStream streamoutput = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(streamoutput, System.IO.Compression.CompressionMode.Compress, false); gzip.Write(data, 0, data.Length); gzip.Close(); return streamoutput.ToArray(); }
public static void SaveLevel(Level level, string output) { System.IO.FileStream file = new System.IO.FileStream(output, System.IO.FileMode.Create); System.IO.Compression.GZipStream zips = new System.IO.Compression.GZipStream(file, System.IO.Compression.CompressionMode.Compress); level.Serialize(zips); zips.Close(); }
/// <summary> /// 分析网络数据包并进行转换为信息对象 /// </summary> /// <param name="packs">接收到的封包对象</param> /// <returns></returns> /// <remarks> /// 对于分包消息,如果收到的只是片段并且尚未接收完全,则不会进行解析 /// </remarks> public static IPMessager.Entity.Message ParseToMessage(params Entity.PackedNetworkMessage[] packs) { if (packs.Length == 0 || (packs[0].PackageCount > 1 && packs.Length != packs[0].PackageCount)) { return(null); } //尝试解压缩,先排序 Array.Sort(packs); //尝试解压缩 System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); try { Array.ForEach(packs, s => zip.Write(s.Data, 0, s.Data.Length)); } catch (Exception) { OnDecompressFailed(new DecomprssFailedEventArgs(packs)); return(null); } zip.Close(); ms.Flush(); ms.Seek(0, System.IO.SeekOrigin.Begin); //构造读取流 System.IO.BinaryReader br = new System.IO.BinaryReader(ms, System.Text.Encoding.Unicode); //开始读出数据 IPMessager.Entity.Message m = new FSLib.IPMessager.Entity.Message(packs[0].RemoteIP); m.PackageNo = br.ReadUInt64(); //包编号 ulong tl = br.ReadUInt64(); m.Command = (Define.Consts.Commands)(tl & 0xFF); //命令编码 m.Options = tl & 0xFFFFFF00; //命令参数 m.UserName = br.ReadString(); //用户名 m.HostName = br.ReadString(); //主机名 int length = br.ReadInt32(); m.NormalMsgBytes = new byte[length]; br.Read(m.NormalMsgBytes, 0, length); length = br.ReadInt32(); m.ExtendMessageBytes = new byte[length]; br.Read(m.ExtendMessageBytes, 0, length); if (!Consts.Check(m.Options, Consts.Cmd_All_Option.BinaryMessage)) { m.NormalMsg = System.Text.Encoding.Unicode.GetString(m.NormalMsgBytes, 0, length); //正文 m.ExtendMessage = System.Text.Encoding.Unicode.GetString(m.ExtendMessageBytes, 0, length); //扩展消息 } return(m); }
public static byte[] zipBase64(byte[] rawData) { MemoryStream ms = new MemoryStream(); System.IO.Compression.GZipStream compressedzipStream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true); compressedzipStream.Write(rawData, 0, rawData.Length); compressedzipStream.Close(); return(ms.ToArray()); }
//based in a code of Dario Solera: http://www.codeproject.com/aspnet/ViewStateCompression.asp public byte[] GZipCompress(byte[] data) { MemoryStream output = new MemoryStream(); System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionMode.Compress, true); gzip.Write(data, 0, data.Length); gzip.Close(); return(output.ToArray()); }
/// <summary> /// 压缩 /// </summary> /// <param name="value">值</param> public static byte[] Compress(byte[] value) { var ms = new MicrosoftSystem.IO.MemoryStream(); var cs = new MicrosoftSystem.IO.Compression.GZipStream(ms, MicrosoftSystem.IO.Compression.CompressionMode.Compress, true); cs.Write(value, 0, value.Length); cs.Close(); return(ms.ToArray()); }
} // End Sub ServerThread private static byte[] Compress(byte[] data) { using (System.IO.MemoryStream compressedStream = new System.IO.MemoryStream()) using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(compressedStream, System.IO.Compression.CompressionMode.Compress)) { zipStream.Write(data, 0, data.Length); zipStream.Close(); return(compressedStream.ToArray()); } }
/// <summary> /// In Memory GZip Decompressor /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] DecompressGZip(this byte[] data) { int length = 10000; //10Kb byte[] Ob = new byte[length]; byte[] result = null; MemoryStream ms = null; System.IO.Compression.GZipStream gz = null; try { using (ms = new MemoryStream(data)) { using (gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)) { int a = 0; while ((a = gz.Read(Ob, 0, length)) > 0) { if (a == length) { //result = Concat(result, Ob); result = result.Concat(Ob); } else { //result = Concat(result, Substring(Ob, 0, a)); result = result.Concat(Ob.Substring(0, a)); } } } } } catch { result = null; } finally { if (gz != null) { gz.Close(); gz.Dispose(); } if (ms != null) { ms.Close(); ms.Dispose(); } } return(result); }
public static Level LoadLevel(string input, Game1 game, GFX.TileSet set) { System.IO.FileStream file = new System.IO.FileStream(input, System.IO.FileMode.Open); System.IO.Compression.GZipStream zips = new System.IO.Compression.GZipStream(file, System.IO.Compression.CompressionMode.Decompress); Level level = Level.Deserialize(zips, game, set); zips.Close(); return(level); }
private void DecompressToFile(string source, string dest) { using (System.IO.Compression.GZipStream stream = new System.IO.Compression.GZipStream(new System.IO.FileStream(source, System.IO.FileMode.Open), System.IO.Compression.CompressionMode.Decompress)) using (System.IO.FileStream outstream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { stream.CopyTo(outstream); outstream.Flush(); outstream.Close(); stream.Close(); } }
/// <summary> /// Gzips a string /// </summary> public static byte[] ConvertGzip(string message, System.Text.Encoding encoding) { byte[] data = encoding.GetBytes(message); using (var compressedStream = new System.IO.MemoryStream()) using (var zipStream = new System.IO.Compression.GZipStream(compressedStream, System.IO.Compression.CompressionMode.Compress)) { zipStream.Write(data, 0, data.Length); zipStream.Close(); return(compressedStream.ToArray()); } }
/// <summary> /// 压缩指定文件 /// </summary> public static byte[] CompressBuffer(byte[] data) { using (var ms = new System.IO.MemoryStream()) using (var zs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) { zs.Write(data, 0, data.Length); zs.Close(); ms.Close(); return(ms.ToArray()); } }
/// <summary> /// GZip压缩 /// 核心方法 /// </summary> /// <param name="toZipByteArr">待压缩的byte[]</param> /// <returns>压缩后的byte[]</returns> public static byte[] Compress(byte[] toZipByteArr) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (System.IO.Compression.GZipStream compressedzipStream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { compressedzipStream.Write(toZipByteArr, 0, toZipByteArr.Length); compressedzipStream.Close(); return(ms.ToArray()); } } }
/// <summary> /// In Memory Compression with Gzip /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] CompressGZip(this byte[] data) { byte[] res = null; MemoryStream ms = null; System.IO.Compression.GZipStream gz = null; try { using (ms = new MemoryStream()) { using (gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, false)) { gz.Write(data, 0, data.Length); gz.Close(); } res = ms.ToArray(); } } catch { res = null; } finally { if (gz != null) { gz.Close(); gz.Dispose(); } if (ms != null) { ms.Close(); ms.Dispose(); } } return res; }
/// <summary> /// In Memory Compression with Gzip /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] CompressGZip(this byte[] data) { byte[] res = null; MemoryStream ms = null; System.IO.Compression.GZipStream gz = null; try { using (ms = new MemoryStream()) { using (gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, false)) { gz.Write(data, 0, data.Length); gz.Close(); } res = ms.ToArray(); } } catch { res = null; } finally { if (gz != null) { gz.Close(); gz.Dispose(); } if (ms != null) { ms.Close(); ms.Dispose(); } } return(res); }
public static byte[] GZip(byte[] byteArray) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string return(ms.ToArray()); } }
/// <summary> /// 压缩指定文件 /// </summary> /// <param name="path"></param> /// <param name="destFile"></param> public void CompressFile(string path, string destFile) { using (var ms = new System.IO.MemoryStream()) using (var zs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) { var buffer = System.IO.File.ReadAllBytes(path); zs.Write(buffer, 0, buffer.Length); zs.Close(); ms.Close(); System.IO.File.WriteAllBytes(destFile, ms.ToArray()); } }
private void start() { //Debug.Assert(MAPSIZE == 64, "The BlockBulkTransfer message requires a map size of 64."); for (byte x = 0; x < MAPSIZE; x++) for (byte y = 0; y < MAPSIZE; y += 16) { NetBuffer msgBuffer = infsN.CreateBuffer(); msgBuffer.Write((byte)Infiniminer.InfiniminerMessage.BlockBulkTransfer); if (!compression) { msgBuffer.Write(x); msgBuffer.Write(y); for (byte dy = 0; dy < 16; dy++) for (byte z = 0; z < MAPSIZE; z++) msgBuffer.Write((byte)(infs.blockList[x, y + dy, z])); if (client.Status == NetConnectionStatus.Connected) infsN.SendMessage(msgBuffer, client, NetChannel.ReliableUnordered); } else { //Compress the data so we don't use as much bandwith - Xeio's work var compressedstream = new System.IO.MemoryStream(); var uncompressed = new System.IO.MemoryStream(); var compresser = new System.IO.Compression.GZipStream(compressedstream, System.IO.Compression.CompressionMode.Compress); //Send a byte indicating that yes, this is compressed msgBuffer.Write((byte)255); //Write everything we want to compress to the uncompressed stream uncompressed.WriteByte(x); uncompressed.WriteByte(y); for (byte dy = 0; dy < 16; dy++) for (byte z = 0; z < MAPSIZE; z++) uncompressed.WriteByte((byte)(infs.blockList[x, y + dy, z])); //Compress the input compresser.Write(uncompressed.ToArray(), 0, (int)uncompressed.Length); //infs.ConsoleWrite("Sending compressed map block, before: " + uncompressed.Length + ", after: " + compressedstream.Length); compresser.Close(); //Send the compressed data msgBuffer.Write(compressedstream.ToArray()); if (client.Status == NetConnectionStatus.Connected) infsN.SendMessage(msgBuffer, client, NetChannel.ReliableUnordered); } } conn.Abort(); }
public byte[] compress(byte[] data) { MemoryStream packed = new MemoryStream(); System.IO.Stream packer = new System.IO.Compression.GZipStream( packed, System.IO.Compression.CompressionMode.Compress ); packer.Write(data, 0, data.Length); packer.Close(); return packed.ToArray(); }
public static string lerror = ""; // Gets the last error that occurred in this struct. Similar to the C perror(). #endregion Fields #region Methods public static bool compress(string infile, string outfile) { try { byte[] ifdata = System.IO.File.ReadAllBytes(infile); System.IO.StreamWriter sw = new System.IO.StreamWriter(outfile); System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(sw.BaseStream, System.IO.Compression.CompressionMode.Compress); gzs.Write(ifdata, 0, ifdata.Length); gzs.Close(); gzs.Dispose(); } catch (System.Exception ex) { lerror = ex.Message; return false; } return true; }
/// <summary> /// Compress contents to gzip /// </summary> /// <param name="s"></param> /// <returns></returns> /// <remarks></remarks> public static byte[] GZIP(ref string s) { byte[] buffer = null; byte[] compressedData = null; MemoryStream oMemoryStream = null; System.IO.Compression.GZipStream compressedzipStream = null; oMemoryStream = new MemoryStream(); buffer = System.Text.Encoding.UTF8.GetBytes(s); compressedzipStream = new System.IO.Compression.GZipStream(oMemoryStream, System.IO.Compression.CompressionMode.Compress, true); compressedzipStream.Write(buffer, 0, buffer.Length); compressedzipStream.Dispose(); compressedzipStream.Close(); compressedData = oMemoryStream.ToArray(); oMemoryStream.Close(); return compressedData; }
/// <summary> /// DataSet���л���ѹ�� /// </summary> /// <param name="ds"></param> /// <returns></returns> public static byte[] CompressDataSet(DataSet ds) { byte[] compressedBuf; #region serialize RawSerializer rs = new RawSerializer(); byte[] buf = rs.Serialize(ds); #endregion System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true); gs.Write(buf, 0, buf.Length); gs.Close(); compressedBuf = ms.ToArray(); return compressedBuf; }
/// <summary> /// �������л���ѹ�� /// </summary> /// <param name="ds"></param> /// <returns></returns> public static byte[] Compress(object obj, Type type) { byte[] compressedBuf; CompressionSerialize compressionSerialize = new CompressionSerialize(); #region serialize byte[] buf = compressionSerialize.Serialize(obj, type); #endregion System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true); gs.Write(buf, 0, buf.Length); gs.Close(); compressedBuf = ms.ToArray(); return compressedBuf; }
/// <summary> /// In Memory Compression with Gzip /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] GZip_Compress(this byte[] data) { byte[] res = null; MemoryStream ms = null; System.IO.Compression.GZipStream gz = null; using (ms = new MemoryStream()) { using (gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, false)) { gz.Write(data, 0, data.Length); gz.Close(); } res = ms.ToArray(); ms.Close(); } return res; }
// <summary> /// 对byte数组进行压缩 /// </summary> /// <param name="data">待压缩的byte数组</param> /// <returns>压缩后的byte数组</returns> public static byte[] Compress(byte[] data) { try { MemoryStream ms = new MemoryStream(); System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true); zip.Write(data, 0, data.Length); zip.Close(); byte[] buffer = new byte[ms.Length]; ms.Position = 0; ms.Read(buffer, 0, buffer.Length); ms.Close(); return buffer; } catch (Exception e) { throw new Exception(e.Message); } }
public static bool decompress(string infile, string outfile) { try { System.IO.StreamWriter sw = new System.IO.StreamWriter(outfile); System.IO.StreamReader sr = new System.IO.StreamReader(infile); System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(sr.BaseStream, System.IO.Compression.CompressionMode.Decompress); int lbyte = gzs.ReadByte(); while (lbyte != -1) { sw.BaseStream.WriteByte((byte) lbyte); lbyte = gzs.ReadByte(); } gzs.Close(); gzs.Dispose(); sw.Close(); sw.Dispose(); } catch (System.Exception ex) { lerror = ex.Message; return false; } return true; }
public static string Zip(string s) { //Transform string into byte[] byte[] byteArray = new byte[s.Length]; int indexBA = 0; foreach (char item in s.ToCharArray()) { byteArray[indexBA++] = (byte)item; } //Prepare for compress using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) using (System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) { //Compress sw.Write(byteArray, 0, byteArray.Length); //Close, DO NOT FLUSH cause bytes will go missing... sw.Close(); //Transform byte[] zip data to string byteArray = ms.ToArray(); ms.Close(); System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length); foreach (byte item in byteArray) { sB.Append((char)item); } //// check if we didn't gain anything //if (sB.Length <= s.Length) //{ // return s; //} return sB.ToString(); } }
static void Main(string[] args) { System.IO.Stream packer = new System.IO.Compression.GZipStream( System.Console.OpenStandardOutput(), System.IO.Compression.CompressionMode.Compress ); MemoryStream buf = new MemoryStream(); System.IO.Stream stdin = System.Console.OpenStandardInput(); byte[] chunk = new byte[10240]; int n = stdin.Read(chunk, 0, chunk.Length); while (n > 0) { buf.Write(chunk, 0, n); n = stdin.Read(chunk, 0, chunk.Length); } packer.Write(buf.GetBuffer(), 0, (int)buf.Length); packer.Close(); }
public void Write(string filename) { string temp = Path.GetTempFileName(); //作成する圧縮ファイルのFileStreamを作成する System.IO.FileStream compFileStrm = new System.IO.FileStream(temp, System.IO.FileMode.Create); //圧縮モードのGZipStreamを作成する System.IO.Compression.GZipStream gzipStrm = new System.IO.Compression.GZipStream(compFileStrm, System.IO.Compression.CompressionMode.Compress); //ファイルに書き込む ds.WriteXml(gzipStrm); gzipStrm.Close(); File.Copy(temp, filename, true); try { File.Delete(temp); } catch { } }
public void accept(string txtName) { textName = txtName; string type = Request.ContentType; int separator = type.IndexOf("/"); string compressionFormat = type.Substring(separator+1); int len = txtName.Length; //compress byte[] stringToByte=new byte[len+1]; int byteIndex=0; foreach(char c in txtName.ToCharArray()) { stringToByte[byteIndex++] = (byte)c; } var bytes = Encoding.ASCII.GetBytes(txtName); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gzipStream = new System.IO.Compression.GZipStream(memoryStream,System.IO.Compression.CompressionMode.Compress); gzipStream.Write(bytes,0,bytes.Length); gzipStream.Close(); stringToByte = memoryStream.ToArray(); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(stringToByte.Length); foreach(byte b in stringToByte) { stringBuilder.Append((char)b); } memoryStream.Close(); gzipStream.Dispose(); memoryStream.Dispose(); string s = stringBuilder.ToString(); //Decompress byte[] decompressStream=new byte[s.Length]; byteIndex=0; foreach(char c in s.ToCharArray()) { decompressStream[byteIndex++]=(byte)c; } System.IO.MemoryStream ms = new System.IO.MemoryStream(decompressStream); System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms,System.IO.Compression.CompressionMode.Decompress); int byteRead = gs.Read(decompressStream,0,decompressStream.Length); System.Text.StringBuilder builder = new System.Text.StringBuilder(byteRead); foreach(byte b in decompressStream) { builder.Append((char)b); } ms.Close(); gs.Close(); ms.Dispose(); gs.Dispose(); String str = builder.ToString(); int a = 0; }
public void Read(string filename) { //展開する書庫のFileStreamを作成する System.IO.FileStream gzipFileStrm = new System.IO.FileStream( filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); //圧縮解除モードのGZipStreamを作成する System.IO.Compression.GZipStream gzipStrm = new System.IO.Compression.GZipStream(gzipFileStrm, System.IO.Compression.CompressionMode.Decompress); //string temp = Path.GetTempFileName(); //展開先のファイルのFileStreamを作成する //System.IO.FileStream outFileStrm = new System.IO.FileStream( // temp, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.MemoryStream outFileStrm = new MemoryStream(); byte[] buffer = new byte[10240]; while (true) { //書庫から展開されたデータを読み込む int readSize = gzipStrm.Read(buffer, 0, buffer.Length); //最後まで読み込んだ時は、ループを抜ける if (readSize == 0) break; //展開先のファイルに書き込む outFileStrm.Write(buffer, 0, readSize); } //閉じる //outFileStrm.Close(); gzipStrm.Close(); ds.Clear(); outFileStrm.Position = 0; ds.ReadXml(outFileStrm); }
static byte[] UnGzip(byte[] buffer) { if (buffer[0] == 31 && buffer[1] == 139) { MemoryStream msIn = new MemoryStream(buffer); MemoryStream msOut = new MemoryStream(); System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(msIn, System.IO.Compression.CompressionMode.Decompress); byte[] data = new byte[2048]; while (true) { int count = gzip.Read(data, 0, 2048); msOut.Write(data, 0, count); if (count < 2048) { break; } } gzip.Close(); msOut.Close(); return msOut.ToArray(); } return buffer; }
//public static Type GetTypeFromXML(string xml) //{ // string typename; // int ilt = xml.IndexOf(">"); // int ispace = xml.IndexOf(" "); // if (ispace == -1) ispace = int.MaxValue; // if (ispace > ilt) // { // typename = xml.Substring(1, ilt - 1); // } // else // { // typename = xml.Substring(1, ispace - 1); // } // return (Type)Current.GlobalTypes[typename]; //} public static byte[] GZipMemory(byte[] Buffer) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream GZip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); GZip.Write(Buffer, 0, Buffer.Length); GZip.Close(); byte[] Result = ms.ToArray(); ms.Close(); return Result; }
/// <summary> /// 压缩指定文件 /// </summary> /// <param name="path"></param> /// <param name="destFile"></param> public void CompressFile(string path, string destFile) { using (var ms = new System.IO.MemoryStream()) using (var zs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) { var buffer = System.IO.File.ReadAllBytes(path); zs.Write(buffer, 0, buffer.Length); zs.Close(); ms.Close(); System.IO.File.WriteAllBytes(destFile, ms.ToArray()); } }
public static string UnGZIP(ref byte[] input) { System.IO.MemoryStream oMemoryStream = null; System.IO.Compression.GZipStream oGZipStream = null; int iLength = 0; byte[] byteArray = new byte[100001]; System.Text.StringBuilder oStringBuilder = new System.Text.StringBuilder(); oMemoryStream = new System.IO.MemoryStream(input); oGZipStream = new System.IO.Compression.GZipStream(oMemoryStream, System.IO.Compression.CompressionMode.Decompress); oMemoryStream.Flush(); oGZipStream.Flush(); do { iLength = oGZipStream.Read(byteArray, 0, byteArray.Length); if (iLength < 1) break; // TODO: might not be correct. Was : Exit Do oStringBuilder.Append(System.Text.Encoding.UTF8.GetString(byteArray, 0, iLength)); } while (true); oGZipStream.Close(); oMemoryStream.Close(); oGZipStream.Dispose(); oMemoryStream.Dispose(); return oStringBuilder.ToString(); }
/// <summary> /// �����ѹ���������л� /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static object Decompress(byte[] buffer, Type type) { System.IO.MemoryStream ms3 = new System.IO.MemoryStream(); System.IO.MemoryStream ms2 = new System.IO.MemoryStream(buffer); System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms2, System.IO.Compression.CompressionMode.Decompress); byte[] writeData = new byte[4096]; while (true) { int size = gs.Read(writeData, 0, writeData.Length); if (size > 0) { ms3.Write(writeData, 0, size); } else { break; } } gs.Close(); ms3.Flush(); byte[] DecompressBuf = ms3.ToArray(); #region deserialize CompressionSerialize compressionSerialize = new CompressionSerialize(); return compressionSerialize.Deserialize(DecompressBuf); #endregion }
/// <summary> /// Сохранить стиль диаграммы в строку. /// </summary> /// <returns>Сохраненные настройки стиля.</returns> public string SaveStyle() { #region Куски старого механизма сохранения стилей // После считывания сохраненного стиля многое ломается. // Например PMEDIAINFOVISDEV-1827. //string style = base.SaveState(); //XmlDocument doc = new XmlDocument(); //doc.LoadXml(style); //XmlNode chartAreaNode = doc.SelectSingleNode("//DefaultChartArea"); //chartAreaNode = doc.SelectSingleNode("//ChartArea"); //RemoveChildNode(chartAreaNode, "YAxis/Label"); //RemoveChildNode(chartAreaNode, "XAxis/Label"); //RemoveChildNode(chartAreaNode, "YAxis/ZeroTick"); //RemoveChildNode(chartAreaNode, "XAxis/ZeroTick"); ////RemoveChildNode(chartAreaNode, "YAxis/DefaultTick");+ // Нельзя убирать, здесь сохраняется шрифт осей ////RemoveChildNode(chartAreaNode, "XAxis/DefaultTick");+ //chartAreaNode.SelectSingleNode("XAxis").Attributes["InstanceID"].Value = null; //chartAreaNode.SelectSingleNode("YAxis").Attributes["InstanceID"].Value = null; //XmlNode node = doc.SelectSingleNode("*/YAxis"); //node.ParentNode.RemoveChild(node); //node = doc.SelectSingleNode("*/XAxis"); //node.ParentNode.RemoveChild(node); //StringBuilder builder = new StringBuilder(); //XmlWriter writer = XmlWriter.Create(builder); //doc.WriteTo(writer); //writer.Close(); #endregion //SoapFormatter formatter = new SoapFormatter(); XmlSerializer serializer = new XmlSerializer(typeof(ChartSettingsWrapper)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); ChartSettingsWrapper my = new ChartSettingsWrapper(this); //formatter.Serialize(gzs, my); serializer.Serialize(gzs, my); gzs.Close(); ms.Close(); string r = Convert.ToBase64String(ms.ToArray()); return r; }
private int _Search() { try { GrooveJSON JSON = new GrooveJSON(); JSON.WriteHeader("getSearchResultsEx"); Dictionary<string, object> searchParams = new Dictionary<string, object>(); searchParams.Add("query", _searchString); searchParams.Add("type", "Songs"); searchParams.Add("guts", 0); searchParams.Add("ppOverride", false); JSON.WriteParameters(searchParams); JSON.WriteMethod("getSearchResultsEx"); JSON.WriteFinish(); string postJSON = JSON.ToString(); HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://cowbell.grooveshark.com/more.php?getSearchResultsEx"); req.Method = "POST"; req.ContentLength = postJSON.Length; req.ContentType = "application/json"; req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); System.IO.Stream postWriteStream = req.GetRequestStream(); byte[] writeBuf = Encoding.ASCII.GetBytes(postJSON); postWriteStream.Write(writeBuf, 0, writeBuf.Length); postWriteStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); System.IO.Compression.GZipStream decompress = new System.IO.Compression.GZipStream(res.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress); string responseJSON = ""; System.IO.StreamReader decompressRead = new System.IO.StreamReader(decompress, Encoding.ASCII); responseJSON = decompressRead.ReadToEnd(); decompressRead.Close(); decompress.Close(); res.Close(); Dictionary<string, object> ResponseDictionary = JSON.Read(responseJSON); return _ParseResponse(ResponseDictionary); } catch (Exception) { return -1; } }
private static System.IO.StreamReader GetDecompressedMergeData(byte[] mergeData) { System.IO.MemoryStream ms = null; System.IO.Compression.GZipStream gs = null; System.IO.StreamReader sr = null; if (mergeData != null) { try { ms = new System.IO.MemoryStream(mergeData); try { gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); } catch { ms.Close(); } sr = new System.IO.StreamReader(gs); gs = null; } finally { if (gs != null) { gs.Close(); } } } return sr; }
internal void threadproc() { const int MAX_SIZE_PER_RECEIVE = 0x400 * 64; byte[] fbuf = new byte[MAX_SIZE_PER_RECEIVE]; for (; ; ) { dfs.DfsFile.FileNode node; int partnum; lock (this) { if (nextpart >= parts.Count) { break; } partnum = nextpart; node = parts[nextpart++]; } string localfullname = localstartname + partnum.ToString() + localendname; using (System.IO.FileStream _fs = new System.IO.FileStream(localfullname, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.Read, FILE_BUFFER_SIZE)) { System.IO.Stream fs = _fs; //if (localendname.EndsWith(".gz")) { fs = new System.IO.Compression.GZipStream(_fs, System.IO.Compression.CompressionMode.Compress); } //string netpath = NetworkPathForHost(node.Host.Split(';')[0]) + @"\" + node.Name; using (System.IO.Stream _fc = new DfsFileNodeStream(node, true, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, FILE_BUFFER_SIZE)) { System.IO.Stream fc = _fc; if (1 == dc.slave.CompressDfsChunks) { fc = new System.IO.Compression.GZipStream(_fc, System.IO.Compression.CompressionMode.Decompress); } { int xread = StreamReadLoop(fc, fbuf, 4); if (4 == xread) { int hlen = MySpace.DataMining.DistributedObjects.Entry.BytesToInt(fbuf); StreamReadExact(fc, fbuf, hlen - 4); } } for (; ; ) { int xread = fc.Read(fbuf, 0, MAX_SIZE_PER_RECEIVE); if (xread <= 0) { break; } fs.Write(fbuf, 0, xread); } fc.Close(); } fs.Close(); try { System.Security.AccessControl.FileSecurity fsec = new System.Security.AccessControl.FileSecurity(); fsec.AddAccessRule(rule); System.IO.File.SetAccessControl(localfullname, fsec); } catch(Exception e) { Console.Error.WriteLine("Error while assigning file permission to: {0}\\{1}", userdomain, dousername); Console.Error.WriteLine(e.ToString()); } } //if (verbose) { Console.Write('*'); ConsoleFlush(); } } }
/// <summary> /// Compress contents to gzip /// </summary> /// <param name="input"></param> /// <returns></returns> /// <remarks></remarks> public static byte[] GZIP(ref byte[] input) { try { byte[] compressedData = null; MemoryStream oMemoryStream = null; System.IO.Compression.GZipStream compressedzipStream = null; oMemoryStream = new MemoryStream(); compressedzipStream = new System.IO.Compression.GZipStream(oMemoryStream, System.IO.Compression.CompressionMode.Compress, false); compressedzipStream.Write(input, 0, input.Length); compressedzipStream.Close(); compressedData = oMemoryStream.ToArray(); compressedzipStream.Dispose(); compressedzipStream.Close(); oMemoryStream.Close(); return compressedData; } catch (Exception ex) { return null; } }