/// <summary> /// decompress gzip data /// </summary> /// <param name="data">compressed data</param> /// <returns></returns> public async static Task<byte[]> Decompress(byte[] data) { MemoryStream ms = null; GZipStream compressedzipStream = null; MemoryStream outBuffer = new MemoryStream(); try { ms = new MemoryStream(data); compressedzipStream = new GZipStream(ms, CompressionMode.Decompress); byte[] block = new byte[1024 * 16]; while (true) { int bytesRead = await compressedzipStream.ReadAsync(block, 0, block.Length); if (bytesRead <= 0) { break; } else { outBuffer.Write(block, 0, bytesRead); } } } finally { if (null != compressedzipStream) compressedzipStream.Close(); if (null != ms) ms.Close(); } return outBuffer.ToArray(); }
void backgroundWorker1DoWork(object sender, DoWorkEventArgs e) { try { var movimentoBancarioService = ResolveComponent<IMovimentoBancarioService>(); var infile = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read); var buffer = new byte[infile.Length]; infile.Read(buffer, 0, buffer.Length); var ms = new MemoryStream(); var compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true); compressedzipStream.Write(buffer, 0, buffer.Length); compressedzipStream.Close(); _id = movimentoBancarioService.Importazione(ms.ToArray(), infile.Length); compressedzipStream.Close(); compressedzipStream.Dispose(); } catch (FileNotFoundException ex) { _log.ErrorFormat("Errore nell'importazione di un file CBI - FILE NON TROVATO - {0} - azienda:{1}", ex, Utility.GetMethodDescription(), Security.Login.Instance.CurrentLogin().Azienda); e.Result = string.Format("Il file '{0}' non è stato trovato", _fileName); } catch (Exception ex) { _log.ErrorFormat("Errore nell'importazione di un file CBI - {0} - azienda:{1}", ex, Utility.GetMethodDescription(), Security.Login.Instance.CurrentLogin().Azienda); throw; } }
private Response CompressResponse(Request request, Response response) { if (!response.ContentType.Contains("image") && request.Headers.AcceptEncoding.Any(x => x.Contains("gzip")) && (!response.Headers.ContainsKey("Content-Encoding") || response.Headers["Content-Encoding"] != "gzip")) { var data = new MemoryStream(); response.Contents.Invoke(data); data.Position = 0; if (data.Length < 1024) { response.Contents = stream => { data.CopyTo(stream); stream.Flush(); }; } else { response.Headers["Content-Encoding"] = "gzip"; response.Contents = s => { var gzip = new GZipStream(s, CompressionMode.Compress, true); data.CopyTo(gzip); gzip.Close(); }; } } return response; }
public static void WriteGzip(XmlDocument theDoc, Stream theStream) { var ms = new MemoryStream(); var xmlSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, ConformanceLevel = ConformanceLevel.Document, Indent = false, NewLineOnAttributes = false, CheckCharacters = true, IndentChars = string.Empty }; XmlWriter tw = XmlWriter.Create(ms, xmlSettings); theDoc.WriteTo(tw); tw.Flush(); tw.Close(); byte[] buffer = ms.GetBuffer(); var compressedzipStream = new GZipStream(theStream, CompressionMode.Compress, true); compressedzipStream.Write(buffer, 0, buffer.Length); // Close the stream. compressedzipStream.Flush(); compressedzipStream.Close(); // Force a flush theStream.Flush(); }
public static byte[] Decompress(byte[] data) { GZipStream gZipStream; using (MemoryStream inputMemoryStream = new MemoryStream()) { inputMemoryStream.Write(data, 0, data.Length); inputMemoryStream.Position = 0; CompressionMode compressionMode = CompressionMode.Decompress; gZipStream = new GZipStream(inputMemoryStream, compressionMode, true); using (MemoryStream outputMemoryStream = new MemoryStream()) { byte[] buffer = new byte[1024]; int byteRead = -1; byteRead = gZipStream.Read(buffer, 0, buffer.Length); while (byteRead > 0) { outputMemoryStream.Write(buffer, 0, byteRead); byteRead = gZipStream.Read(buffer, 0, buffer.Length); } gZipStream.Close(); return outputMemoryStream.ToArray(); } } }
static void Decompress_gz(string gz_file) { FileStream OriginalFileStream = File.OpenRead(gz_file); // This Returns a file stream to read. string extension = Path.GetExtension(gz_file); // This Gets the Extension of the File. string final_filename = gz_file.Substring(0, gz_file.Length - extension.Length); // Getting the File Name without the File Extension. final_filename = final_filename + ".txt"; FileStream decompressedFileStream = File.Create(final_filename); // Creating a File to Store the Decompressed File GZipStream decompressionStream = new GZipStream(OriginalFileStream, CompressionMode.Decompress); // This sets the Decompression of the Original Compressed FileStream. decompressionStream.CopyTo(decompressedFileStream); // Copies the Decompressed File Stream to the desired file. // Closing all the File Handles decompressionStream.Close(); decompressedFileStream.Close(); OriginalFileStream.Close(); // Parsing the Decompressed File. Parse_File(final_filename); Console.WriteLine("Decompressed File Name is " + final_filename); return; }
public static object UnzipObject(IZEntity z) { object result = null; using (MemoryStream zipStream = new MemoryStream(z.Data)) { zipStream.Position = 0; using (GZipStream gZipStream = new GZipStream(zipStream, CompressionMode.Decompress)) { byte[] buffer = new byte[z.Size]; gZipStream.Read(buffer, 0, z.Size); using (MemoryStream ms = new MemoryStream(buffer)) { BinaryFormatter bf = new BinaryFormatter(); ms.Position = 0; result = bf.Deserialize(ms); } if (result.GetType() != z.Type) { throw new InvalidCastException("Decompressed stream does not correspond to source type"); } gZipStream.Close(); } zipStream.Close(); } return result; }
public byte[] DataSetToByte(DataSet ds) { try { ds.RemotingFormat = SerializationFormat.Binary; BinaryFormatter ser = new BinaryFormatter(); MemoryStream unMS = new MemoryStream(); ser.Serialize(unMS, ds); byte[] bytes = unMS.ToArray(); int lenbyte = bytes.Length; MemoryStream compMs = new MemoryStream(); GZipStream compStream = new GZipStream(compMs, CompressionMode.Compress, true); compStream.Write(bytes, 0, lenbyte); compStream.Close(); unMS.Close(); compMs.Close(); byte[] zipData = compMs.ToArray(); return zipData; } catch (Exception ex) { gLogger.ErrorException("DataSetToByte--", ex); throw ex; } }
/// <summary> /// 解压数据 /// </summary> /// <param name="aSourceStream"></param> /// <returns></returns> public static byte[] DeCompress(Stream aSourceStream) { byte[] vUnZipByte = null; GZipStream vUnZipStream; using (MemoryStream vMemory = new MemoryStream()) { vUnZipStream = new System.IO.Compression.GZipStream(aSourceStream, CompressionMode.Decompress); try { byte[] vTempByte = new byte[1024]; int vRedLen = 0; do { vRedLen = vUnZipStream.Read(vTempByte, 0, vTempByte.Length); vMemory.Write(vTempByte, 0, vRedLen); }while (vRedLen > 0); vUnZipStream.Close(); } finally { vUnZipStream.Dispose(); } vUnZipByte = vMemory.ToArray(); } return(vUnZipByte); }
static void Main(string[] args) { GZipStream gzOut = new GZipStream(File.Create(@"C:\Writing1mb.zip"), CompressionMode.Compress); DeflateStream dfOut = new DeflateStream(File.Create(@"C:\Writing1mb2.zip"), CompressionMode.Compress); TextWriter tw = new StreamWriter(gzOut); TextWriter tw2 = new StreamWriter(dfOut); try { for(int i = 0; i < 1000000; i++) { tw.WriteLine("Writing until more than 1mb to ZIP it!"); tw2.WriteLine("Writing until more than 1mb to ZIP it!"); } } catch(Exception) { throw; } finally { tw.Close(); gzOut.Close(); tw2.Close(); dfOut.Close(); } }
public static string GZipUtf8ResultToString(DownloadDataCompletedEventArgs e) { if(e.Cancelled || (e.Error != null) || (e.Result == null)) return null; MemoryStream msZipped = new MemoryStream(e.Result); GZipStream gz = new GZipStream(msZipped, CompressionMode.Decompress); BinaryReader br = new BinaryReader(gz); MemoryStream msUTF8 = new MemoryStream(); while(true) { byte[] pb = null; try { pb = br.ReadBytes(4096); } catch(Exception) { } if((pb == null) || (pb.Length == 0)) break; msUTF8.Write(pb, 0, pb.Length); } br.Close(); gz.Close(); msZipped.Close(); return Encoding.UTF8.GetString(msUTF8.ToArray()); }
public static byte[] GZCompress(byte[] source) { byte[] buffer; if ((source == null) || (source.Length == 0)) { throw new ArgumentNullException("source"); } try { using (MemoryStream stream = new MemoryStream()) { using (GZipStream stream2 = new GZipStream(stream, CompressionMode.Compress, true)) { Console.WriteLine("Compression"); stream2.Write(source, 0, source.Length); stream2.Flush(); stream2.Close(); Console.WriteLine("Original size: {0}, Compressed size: {1}", source.Length, stream.Length); stream.Position = 0L; buffer = stream.ToArray(); } } } catch (Exception exception) { LoggingService.Error("GZip压缩时出错:", exception); buffer = source; } return buffer; }
/// <summary /> internal static byte[] ZipBytes(this byte[] byteArray, bool fast = true) { if (byteArray == null) { return(null); } try { //Prepare for compress using (var ms = new System.IO.MemoryStream()) { var level = System.IO.Compression.CompressionLevel.Fastest; if (!fast) { level = System.IO.Compression.CompressionLevel.Optimal; } using (var sw = new System.IO.Compression.GZipStream(ms, level)) { //Compress sw.Write(byteArray, 0, byteArray.Length); sw.Close(); //Transform byte[] zip data to string return(ms.ToArray()); } } } catch (Exception ex) { throw; } }
/// <summary> /// Decompresses an array of bytes. /// </summary> /// <param name="bytes">The array of bytes to decompress.</param> /// <returns>The decompressed array of bytes.</returns> public static byte[] Decompress(this byte[] bytes) { using (MemoryStream stream = new MemoryStream()) { stream.Write(bytes, 0, bytes.Length); stream.Position = 0; using (GZipStream compressedStream = new GZipStream(stream, CompressionMode.Decompress, true)) { using (MemoryStream output = new MemoryStream()) { byte[] buffer = new byte[32*1024]; int count = compressedStream.Read(buffer, 0, buffer.Length); while (count > 0) { output.Write(buffer, 0, count); count = compressedStream.Read(buffer, 0, buffer.Length); } compressedStream.Close(); return output.ToArray(); } } } }
/// <summary> /// 对byte数组进行压缩 /// </summary> /// <param name="data">待压缩的byte数组</param> /// <returns>压缩后的byte数组</returns> public static byte[] Compress(byte[] data) { try { byte[] buffer = null; using (MemoryStream ms = new MemoryStream()) { using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { zip.Write(data, 0, data.Length); zip.Close(); } 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 ManagedBitmap(string fileName) { try { byte[] buffer = new byte[1024]; using (MemoryStream fd = new MemoryStream()) using (Stream fs = File.OpenRead(fileName)) using (Stream csStream = new GZipStream(fs, CompressionMode.Decompress)) { int nRead; while ((nRead = csStream.Read(buffer, 0, buffer.Length)) > 0) { fd.Write(buffer, 0, nRead); } csStream.Flush(); csStream.Close(); buffer = fd.ToArray(); } Width = buffer[4] << 8 | buffer[5]; Height = buffer[6] << 8 | buffer[7]; _colors = new Color[Width * Height]; int start = 8; for (int i = 0; i < _colors.Length; i++) { _colors[i] = Color.FromArgb(buffer[start], buffer[start + 1], buffer[start + 2], buffer[start + 3]); start += 4; } } catch { LoadedOK = false; } }
/// <summary> /// 反序列化 解压缩 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static object Deserialize(byte[] bytes) { MemoryStream msNew = new MemoryStream(bytes); msNew.Position = 0; GZipStream gzipStream = new GZipStream(msNew, CompressionMode.Decompress);//创建解压对象 byte[] buffer = new byte[4096];//定义数据缓冲 int offset = 0;//定义读取位置 MemoryStream ms = new MemoryStream();//定义内存流 while ((offset = gzipStream.Read(buffer, 0, buffer.Length)) != 0) { ms.Write(buffer, 0, offset);//解压后的数据写入内存流 } BinaryFormatter sfFormatter = new BinaryFormatter();//定义BinaryFormatter以反序列化object对象 ms.Position = 0;//设置内存流的位置 object obj; try { obj = (object)sfFormatter.Deserialize(ms);//反序列化 } catch { throw; } finally { ms.Close();//关闭内存流 ms.Dispose();//释放资源 } gzipStream.Close();//关闭解压缩流 gzipStream.Dispose();//释放资源 msNew.Close(); msNew.Dispose(); return obj; }
/// <summary> /// Compresses an Epi Info 7 data package. /// </summary> /// <param name="fi">The file info for the raw data file that will be compressed.</param> public static void CompressDataPackage(FileInfo fi) { using (FileStream inFile = fi.OpenRead()) { // Prevent compressing hidden and already compressed files. if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fi.Extension != ".gz") { using (FileStream outFile = File.Create(fi.FullName + ".gz")) { using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress)) { // Copy the source file into the compression stream. byte[] buffer = new byte[4096]; int numRead; while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0) { Compress.Write(buffer, 0, numRead); } Compress.Close(); Compress.Dispose(); } } } } }
public static byte[] Decompress(byte[] data) { try { MemoryStream input = new MemoryStream(); input.Write(data, 0, data.Length); input.Position = 0; GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true); MemoryStream output = new MemoryStream(); byte[] buff = new byte[64]; int read = -1; read = gzip.Read(buff, 0, buff.Length); while (read > 0) { output.Write(buff, 0, read); read = gzip.Read(buff, 0, buff.Length); } gzip.Close(); return output.ToArray(); } catch (Exception ex) { VMuktiAPI.VMuktiHelper.ExceptionHandler(ex, "Decompress", "Compressor.cs"); return null; } }
public static byte[] Inflate(byte[] bytes) { MemoryStream ms = new MemoryStream(bytes); MemoryStream output = new MemoryStream(); GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress); byte[] buffer = new byte[BUFFER_SIZE]; try { while (gzip.CanRead) { int bytesRead = gzip.Read(buffer, 0, buffer.Length); if (bytesRead <= 0) break; output.Write(buffer, 0, bytesRead); } } catch (Exception) { } finally { gzip.Close(); ms = null; } return output.ToArray(); }
public string UncompressHandHistory(string compressedHandHistory) { if (compressedHandHistory == null) return null; byte[] byteArray = new byte[compressedHandHistory.Length]; int indexBa = 0; foreach (char item in compressedHandHistory) byteArray[indexBa++] = (byte)item; MemoryStream memoryStream = new MemoryStream(byteArray); GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress); byteArray = new byte[1024]; StringBuilder stringBuilder = new StringBuilder(); int readBytes; while ((readBytes = gZipStream.Read(byteArray, 0, byteArray.Length)) != 0) { for (int i = 0; i < readBytes; i++) stringBuilder.Append((char)byteArray[i]); } gZipStream.Close(); memoryStream.Close(); gZipStream.Dispose(); memoryStream.Dispose(); return stringBuilder.ToString(); }
/// <summary> /// 解压数据 /// </summary> /// <param name="aSourceStream"></param> /// <returns></returns> public static byte[] DeCompress(Stream aSourceStream) { byte[] vUnZipByte = null; GZipStream vUnZipStream; using (MemoryStream vMemory = new MemoryStream()) { vUnZipStream = new GZipStream(aSourceStream, CompressionMode.Decompress); try { byte[] vTempByte = new byte[1024]; int vRedLen = 0; do { vRedLen = vUnZipStream.Read(vTempByte, 0, vTempByte.Length); vMemory.Write(vTempByte, 0, vRedLen); } while (vRedLen > 0); vUnZipStream.Close(); } finally { vUnZipStream.Dispose(); } vUnZipByte = vMemory.ToArray(); } return vUnZipByte; }
public static byte[] DecompressData(byte[] data) { MemoryStream input = new MemoryStream(); input.Write(data, 0, data.Length); input.Position = 0; MemoryStream output; using (GZipStream gZipStream = new GZipStream(input, CompressionMode.Decompress, true)) { output = new MemoryStream(); byte[] buff = new byte[64]; int read = -1; read = gZipStream.Read(buff, 0, buff.Length); while (read > 0) { output.Write(buff, 0, read); read = gZipStream.Read(buff, 0, buff.Length); } gZipStream.Close(); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return output.ToArray(); }
public void FileCompress(string sourceFile, string destinationFile) { // ----- Decompress a previously compressed string. // First, create the input file stream. FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read); // ----- Create the output file stream. FileStream destinationStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write); // ----- Bytes will be processed by a compression // stream. GZipStream compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true); // ----- Process bytes from one file into the other. const int BlockSize = 4096; byte[] buffer = new byte[BlockSize + 1]; int bytesRead = default(int); do { bytesRead = sourceStream.Read(buffer, 0, BlockSize); if (bytesRead == 0) { break; } compressedStream.Write(buffer, 0, bytesRead); } while (true); // ----- Close all the streams. sourceStream.Close(); compressedStream.Close(); destinationStream.Close(); }
public static byte[] Decompress(byte[] bytData) { using (MemoryStream oMS = new MemoryStream(bytData)) { using (GZipStream oGZipStream = new GZipStream(oMS, CompressionMode.Decompress)) { const int CHUNK = 1024; int intTotalBytesRead = 0; do { Array.Resize(ref bytData, intTotalBytesRead + CHUNK); int intBytesRead = oGZipStream.Read(bytData, intTotalBytesRead, CHUNK); intTotalBytesRead += intBytesRead; if (intBytesRead < CHUNK) { Array.Resize(ref bytData, intTotalBytesRead); break; } } while (true); oGZipStream.Close(); } oMS.Close(); } return bytData; }
private IEnumerator DoUploadData() { using (var inputStream = new MemoryStream()) { var data = Encoding.UTF8.GetBytes(dataCache); var gZip = new System.IO.Compression.GZipStream(inputStream, System.IO.Compression.CompressionMode.Compress); gZip.Write(data, 0, data.Length); gZip.Close(); var toUploadData = Convert.ToBase64String(inputStream.ToArray()); if (null != toUploadData && toUploadData.Length > 0) { using (var request = UnityEngine.Networking.UnityWebRequest.Put(serverUrl, toUploadData)) { yield return(request.SendWebRequest()); if (request.isHttpError || request.isNetworkError) { LogUtil.DebugLog("send data error: " + request.error); } else { LogUtil.DebugLog("send data success: " + dataCache); dataCache = ""; } } } gZip.Dispose(); } }
/// <summary> /// 使用execute生成静态页面 /// </summary> /// <param name="aspxPath"></param> /// <param name="htmlPath"></param> /// <param name="encode"></param> /// <param name="isGzip"></param> public static void AspxToHtml(string aspxPath, string htmlPath, System.Text.Encoding encode, bool isGzip) { using (Stream stream = new FileStream(htmlPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (isGzip) { using (GZipStream gzip = new GZipStream(stream, CompressionMode.Compress)) { using (StreamWriter sw = new StreamWriter(gzip, encode)) { HttpContext.Current.Server.Execute(aspxPath, sw, true); sw.Flush(); sw.Close(); } gzip.Close(); } } else { using (StreamWriter sw = new StreamWriter(stream, encode)) { HttpContext.Current.Server.Execute(aspxPath, sw, true); sw.Flush(); sw.Close(); } } } }
public static string UnzipString(string unCompressedString) { System.Text.StringBuilder uncompressedString = new System.Text.StringBuilder(); byte[] writeData = new byte[4096]; byte[] bytData = System.Convert.FromBase64String(unCompressedString); int totalLength = 0; int size = 0; Stream s = new GZipStream(new MemoryStream(bytData), CompressionMode.Decompress); while (true) { size = s.Read(writeData, 0, writeData.Length); if (size > 0) { totalLength += size; uncompressedString.Append(System.Text.Encoding.UTF8.GetString(writeData, 0, size)); } else { break; } } s.Close(); return uncompressedString.ToString(); }
public byte[] Decompress(byte[] input) { if (input == null) { throw new ArgumentNullException("input"); } var output = new List<byte>(); using (var ms = new MemoryStream(input)) { var gs = new GZipStream(ms, CompressionMode.Decompress); var readByte = gs.ReadByte(); while (readByte != -1) { output.Add((byte)readByte); readByte = gs.ReadByte(); } gs.Close(); ms.Close(); } return output.ToArray(); }
public static string Zip(string value) { //Transform string into byte[] byte[] byteArray = new byte[value.Length]; int indexBA = 0; char[] charArray = value.ToCharArray(); foreach (char item in charArray) { 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> /// Compresses a file with the gzip algorithm. /// (If you want to keep the correct file name in the archive you must set the dest /// path value equals to source + ".gz") /// </summary> /// <param name="source">The source file path.</param> /// <param name="dest">The destination file path.</param> /// <returns>True if the file have been successfully compressed.</returns> public static bool compressFile(string source, string dest) { try { // Stream to read the file FileStream fstream = new FileStream(source, FileMode.Open, FileAccess.Read); // We store the complete file into a buffer byte[] buf = new byte[fstream.Length]; fstream.Read(buf, 0, buf.Length); fstream.Close(); // Stream to write the compressed file fstream = new FileStream(dest, FileMode.Create); // File compression (fstream is automatically closed) GZipStream zipStream = new GZipStream(fstream, CompressionMode.Compress, false); zipStream.Write(buf, 0, buf.Length); zipStream.Close(); return true; } catch (Exception e) { MailMgr.Logger.Error(e); return false; } }
/// <summary> /// GZip解压函数 /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] GZipDecompress(byte[] data) { int bufferSize = 256; using (MemoryStream stream = new MemoryStream()) { using (GZipStream gZipStream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress)) { byte[] bytes = new byte[bufferSize]; int n; while ((n = gZipStream.Read(bytes, 0, bytes.Length)) != 0) { stream.Write(bytes, 0, n); } gZipStream.Close(); gZipStream.Dispose(); } byte[] rdata = stream.ToArray(); stream.Close(); stream.Dispose(); return rdata; } }
public static Stream GetStream(Stream fileStream) { Stream objFileStream = null; try { GZipStream gzip = new GZipStream(fileStream, CompressionMode.Decompress); MemoryStream memStream = new MemoryStream(); byte[] bytes = new byte[1024]; int bytesRead = -1; while (bytesRead != 0) { bytesRead = gzip.Read(bytes, 0, 1024); memStream.Write(bytes, 0, bytesRead); memStream.Flush(); } memStream.Position = 0; objFileStream = memStream; gzip.Close(); gzip.Dispose(); fileStream.Dispose(); } catch (Exception) { fileStream.Position = 0; objFileStream = fileStream; } return objFileStream; }
public static byte[] ZipToByte(string value, Encoding encode, bool useGzip = false) { byte[] byteArray = encode.GetBytes(value); byte[] data = null; //Prepare for compress System.IO.MemoryStream ms = new System.IO.MemoryStream(); if (useGzip) { 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(); sw.Dispose(); } else { ms.Write(byteArray, 0, byteArray.Length); } data = ms.ToArray(); //Transform byte[] zip data to string ms.Close(); ms.Dispose(); return(data); }
public string CompressHandHistory(string fullHandText) { if (fullHandText == null) return null; //Transform string into byte[] byte[] byteArray = new byte[fullHandText.Length]; int indexBA = 0; foreach (char item in fullHandText.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> /// 压缩数据组 /// </summary> /// <param name="source"></param> /// <returns></returns> public static byte[] Compress(this byte[] source) { using (var ms = new System.IO.MemoryStream()) using (var gzip = new System.IO.Compression.GZipStream(ms, CompressionMode.Compress)) { gzip.Write(source); gzip.Close(); return(ms.ToArray()); } }
/// <summary> /// gzip压缩 /// </summary> /// <param name="inputBytes"></param> /// <returns></returns> public static byte[] Compress(byte[] inputBytes) { using (MemoryStream ms = new MemoryStream(inputBytes.Length)) { using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) { gzip.Write(inputBytes, 0, inputBytes.Length); gzip.Flush(); gzip.Close(); } return(ms.ToArray()); } }
public static void unZipStream(string path) { FileStream fstream = new FileStream(path, FileMode.Open, FileAccess.Read); System.IO.Compression.GZipStream gstream = new System.IO.Compression.GZipStream(fstream, System.IO.Compression.CompressionMode.Decompress); StreamReader reader = new StreamReader(gstream); string cstring = reader.ReadToEnd(); WriteStringToFile(path + ".bak", cstring, false); reader.Close(); gstream.Close(); fstream.Close(); }
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()); } }
private void SaveConfig() { MemoryStream ms = new MemoryStream(); BinaryFormatter binFormat = new BinaryFormatter(); binFormat.Serialize(ms, config); byte[] SerializeByte = ms.ToArray(); FileStream fs = new FileStream(@".\config.bin", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); GZipStream compressedStream = new System.IO.Compression.GZipStream(fs, CompressionMode.Compress, true); compressedStream.Write(SerializeByte, 0, SerializeByte.Length); compressedStream.Flush(); compressedStream.Close(); fs.Close(); }
/// <summary> /// Zips the specified un-zipped stream. /// </summary> /// <param name="unZipStream">The stream to zip.</param> /// <param name="zipStream">The stream that will contain the zipper data.</param> /// <param name="zipStreamPosition">Set the zip stream position.</param> public static void Compress(MemoryStream unZipStream, MemoryStream zipStream, long zipStreamPosition = 0) { // Set the position. unZipStream.Position = zipStreamPosition; // Create all the streams using (System.IO.Compression.GZipStream stream = new System.IO.Compression.GZipStream(zipStream, CompressionMode.Compress, true)) { // Compress the data. unZipStream.CopyTo(stream); // Cleanup the resources. stream.Close(); } }
/// <summary> /// Zips the specified zip file. /// </summary> /// <param name="unZipFilename">The file to zip.</param> /// <param name="zipFilename">The file that will contain the zipper data.</param> public static void Compress(string unZipFilename, string zipFilename) { // Create all the streams using (Stream zipStream = File.Create(zipFilename)) using (Stream unzipStream = File.OpenRead(unZipFilename)) using (System.IO.Compression.GZipStream stream = new System.IO.Compression.GZipStream(zipStream, CompressionMode.Compress)) { // Compress the data. unzipStream.CopyTo(stream); // Cleanup the resources. stream.Close(); zipStream.Close(); unzipStream.Close(); } }
/// <summary> /// オブジェクトの内容をファイルに保存する /// </summary> /// <param name="obj">保存するオブジェクト</param> /// <param name="path">保存先のファイル名</param> public static void SaveToZipBinaryFile(object obj, string gzipFile) { //作成する圧縮ファイルのFileStreamを作成する System.IO.FileStream compFileStrm = new System.IO.FileStream(gzipFile, System.IO.FileMode.Create); //圧縮モードのGZipStreamを作成する System.IO.Compression.GZipStream gzipStrm = new System.IO.Compression.GZipStream(compFileStrm, System.IO.Compression.CompressionMode.Compress); BinaryFormatter bf = new BinaryFormatter(); //シリアル化して書き込む bf.Serialize(gzipStrm, obj); gzipStrm.Close(); }
public static byte[] GZipDecompress(byte[] ts) { MemoryStream srcMs = new MemoryStream(ts); System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(srcMs, System.IO.Compression.CompressionMode.Decompress); MemoryStream ms = new MemoryStream(); byte[] bytes = new byte[40960]; int n; while ((n = zipStream.Read(bytes, 0, bytes.Length)) > 0) { ms.Write(bytes, 0, n); } zipStream.Close(); return(ms.ToArray()); }
static public void CompressFile(string sourceFile, string destinationFile) { int checkCounter; if (System.IO.File.Exists(sourceFile) == false) { return; } byte[] buffer; System.IO.FileStream sourceStream = null; System.IO.FileStream destinationStream = null; //System.IO.Compression.DeflateStream compressedStream = null; System.IO.Compression.GZipStream compressedStream = null; try { sourceStream = new System.IO.FileStream(sourceFile, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read); buffer = new byte[Convert.ToInt64(sourceStream.Length)]; checkCounter = sourceStream.Read(buffer, 0, buffer.Length); //output (ZIP) file name destinationStream = new System.IO.FileStream(destinationFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); // Create a compression stream pointing to the destiantion stream compressedStream = new System.IO.Compression.GZipStream(destinationStream, System.IO.Compression.CompressionMode.Compress, true); compressedStream.Write(buffer, 0, buffer.Length); } finally { // Make sure we allways close all streams if (sourceStream != null) { sourceStream.Close(); } if (compressedStream != null) { compressedStream.Close(); } if (destinationStream != null) { destinationStream.Close(); } } }
public void testGzipStream() { // make sure compression works, file should be smaller string sample = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files", "fp.log"); byte[] uncompressed = File.ReadAllBytes(sample); int before = uncompressed.Length; byte[] compressed; int after = 0; // test gzip stream compression code using (MemoryStream compressStream = new MemoryStream()) using (ZopfliStream compressor = new ZopfliStream(compressStream, ZopfliFormat.ZOPFLI_FORMAT_GZIP)) { compressor.Write(uncompressed, 0, before); compressor.Close(); compressed = compressStream.ToArray(); after = compressed.Length; } before.Should().BeGreaterThan(after); // make sure we can decompress the file using built-in .net byte[] decompressedBytes = new byte[before]; using (MemoryStream tempStream = new MemoryStream(compressed)) using (System.IO.Compression.GZipStream decompressionStream = new System.IO.Compression.GZipStream(tempStream, System.IO.Compression.CompressionMode.Decompress)) { decompressionStream.Read(decompressedBytes, 0, before); } uncompressed.Should().Equal(decompressedBytes); // use built-in .net compression and make sure zopfil is smaller int after_builtin = 0; using (MemoryStream compressStream = new MemoryStream()) using (System.IO.Compression.GZipStream compressor = new System.IO.Compression.GZipStream(compressStream, System.IO.Compression.CompressionLevel.Optimal)) { compressor.Write(uncompressed, 0, before); compressor.Close(); after_builtin = compressStream.ToArray().Length; } after_builtin.Should().BeGreaterThan(after); }
private void btn_send_Click(object sender, EventArgs e) { saveFileDialog1.ShowDialog(); using (FileStream sw = new FileStream(saveFileDialog1.FileName, FileMode.Create)) { TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); CryptoStream encStream = new CryptoStream(sw, tdes.CreateEncryptor(exportfilepassword.key, exportfilepassword.vec), CryptoStreamMode.Write ); System.IO.Compression.GZipStream gcp = new System.IO.Compression.GZipStream(encStream, CompressionMode.Compress, false); byte[] bt_buff = System.Text.Encoding.Default.GetBytes(txt_msg.Text); gcp.Write(bt_buff, 0, bt_buff.Length); gcp.Close(); } txt_msg.Text = ""; }
/// <summary> /// オブジェクトの内容をファイルから読み込み復元する /// </summary> /// <param name="path">読み込むファイル名</param> /// <returns>復元されたオブジェクト</returns> public static object LoadFromZipBinaryFile(string gzipFile) { //展開する書庫のFileStreamを作成する System.IO.FileStream gzipFileStrm = new System.IO.FileStream( gzipFile, 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); BinaryFormatter f = new BinaryFormatter(); //読み込んで逆シリアル化する object obj = f.Deserialize(gzipStrm); gzipStrm.Close(); return(obj); }
private void ReadConfig() { MemoryStream ms = new MemoryStream(); byte[] SerializeByte = ms.ToArray(); FileStream fs = new FileStream(@".\config.bin", FileMode.OpenOrCreate, FileAccess.Read, FileShare.None); GZipStream compressedStream = new System.IO.Compression.GZipStream(fs, CompressionMode.Decompress, true); compressedStream.CopyTo(ms); ms.Position = 0; BinaryFormatter binFormat = new BinaryFormatter(); if (ms.Length != 0) { config = (Config)binFormat.Deserialize(ms); } fs.Close(); ms.Close(); compressedStream.Close(); }
public static string UnZip(string value) { var inputByteArray = new byte[value.Length / 2]; for (var x = 0; x < inputByteArray.Length; x++) { var i = Convert.ToInt32(value.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } //Transform string into byte[] byte[] byteArray = inputByteArray; //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 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 DecompressBase64String(string pBase64Str) { System.Text.Encoding encoder = Encoding.UTF8; //byte[] compressedData = encoder.GetBytes(xmlFile); byte[] compressedData = Convert.FromBase64String(pBase64Str); byte[] writeData = new byte[1024 * 1024]; System.IO.Stream zipStream = new System.IO.Compression.GZipStream(new System.IO.MemoryStream(compressedData), System.IO.Compression.CompressionMode.Decompress); int totalLength = 0; int size; string sResult = string.Empty; while ((size = zipStream.Read(writeData, 0, writeData.Length)) > 0) { totalLength += size; sResult += encoder.GetString(writeData, 0, size); } zipStream.Close(); // _Logger.Debug("compressed Lenght: " + compressedData.Length + " de compressed Lenght: " + totalLength); return(sResult); }
public static string UnZip(string value) { System.Text.StringBuilder sB = new StringBuilder(); //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); List <byte> byteList = new List <byte>(); //Reset variable to collect uncompressed result //byteArray = new byte[byteArray.Length * 3 ]; int data = sr.ReadByte(); while (data != -1) { //sB.Append((char)data); byteList.Add((byte)data); data = sr.ReadByte(); } //Decompress sB.Append(Encoding.UTF8.GetString(byteList.ToArray())); //Transform byte[] unzip data to string //Read the number of bytes GZipStream red and do not a for each bytes in sr.Close(); ms.Close(); sr.Dispose(); ms.Dispose(); return(sB.ToString()); }
public static string UnZip(StreamReader ms) { //Transform string into byte[] //byte[] byteArray = new byte[ms.Length]; //ms.Read(byteArray, 0, ms.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.BaseStream, System.IO.Compression.CompressionMode.Decompress); //sr.Position = 0; //Reset variable to collect uncompressed result String ret = ""; //Decompress //int rByte = sr.Read(byteArray, 0, byteArray.Length); using (var srs = new StreamReader(sr)) { ret = srs.ReadToEnd(); srs.Close(); srs.Dispose(); } sr.Close(); ms.Close(); sr.Dispose(); ms.Dispose(); return(ret); }
/// <summary> /// 获得消息包的字节流 /// </summary> /// <param name="remoteIp">远程主机地址</param> /// <param name="packageNo">包编号</param> /// <param name="command">命令</param> /// <param name="options">参数</param> /// <param name="userName">用户名</param> /// <param name="hostName">主机名</param> /// <param name="content">正文消息</param> /// <param name="extendContents">扩展消息</param> /// <returns></returns> public static Entity.PackedNetworkMessage[] BuildNetworkMessage(IPEndPoint remoteIp, ulong packageNo, Define.Consts.Commands command, ulong options, string userName, string hostName, byte[] content, byte[] extendContents) { options |= (ulong)Define.Consts.Cmd_Send_Option.Content_Unicode; //每次发送所能容下的数据量 var maxBytesPerPackage = Define.Consts.MAX_UDP_PACKAGE_LENGTH - PackageHeaderLength; //压缩数据流 var ms = new System.IO.MemoryStream(); var zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); var bw = new System.IO.BinaryWriter(zip, System.Text.Encoding.Unicode); //写入头部数据 bw.Write(packageNo); //包编号 bw.Write(((ulong)command) | options); //命令|选项 bw.Write(userName); //用户名 bw.Write(hostName); //主机名 bw.Write(content == null ? 0 : content.Length); //数据长度 //写入消息数据 if (content != null) { bw.Write(content); } bw.Write(extendContents == null ? 0 : extendContents.Length); //补充数据长度 if (extendContents != null) { bw.Write(extendContents); } bw.Close(); zip.Close(); ms.Flush(); ms.Seek(0, System.IO.SeekOrigin.Begin); //打包数据总量 var dataLength = (int)ms.Length; var packageCount = (int)Math.Ceiling(dataLength * 1.0 / maxBytesPerPackage); var pnma = new PackedNetworkMessage[packageCount]; for (var i = 0; i < packageCount; i++) { var count = i == packageCount - 1 ? dataLength - maxBytesPerPackage * (packageCount - 1) : maxBytesPerPackage; var buf = new byte[count + PackageHeaderLength]; buf[0] = VersionHeader; BitConverter.GetBytes(packageNo).CopyTo(buf, 1); BitConverter.GetBytes(dataLength).CopyTo(buf, 9); BitConverter.GetBytes(packageCount).CopyTo(buf, 13); BitConverter.GetBytes(i).CopyTo(buf, 17); buf[21] = Define.Consts.Check(options, Define.Consts.Cmd_All_Option.RequireReceiveCheck) ? (byte)1 : (byte)0; //包确认标志? ms.Read(buf, 32, buf.Length - 32); pnma[i] = new Entity.PackedNetworkMessage() { Data = buf, PackageCount = packageCount, PackageIndex = i, PackageNo = packageNo, RemoteIP = remoteIp, SendTimes = 0, Version = 2, IsReceiveSignalRequired = buf[21] == 1 }; } ms.Close(); return(pnma); }
//读取配置文件 public static IEnumerator readVersionText() { mStreamBundleList.Clear(); string fullPath = BundleConfig.appOutputPath + BundleConfig.resourceOldVersionFileName; #if UNITY_EDITOR fullPath = "file:///" + fullPath; #elif UNITY_ANDROID fullPath = BundleConfig.apkPath + BundleConfig.resourceOldVersionFileName; #endif WWW www = new WWW(fullPath); yield return(www); if (string.IsNullOrEmpty(www.error) == false) { yield break; } string[] lines; MemoryStream stream = null; System.IO.Compression.GZipStream gstream = null; StreamReader reader = null; try { stream = new MemoryStream(www.bytes); gstream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress); reader = new StreamReader(gstream); string cstring = reader.ReadToEnd(); lines = cstring.Split('\n'); } catch { lines = www.text.Split('\n'); } if (reader != null) { reader.Close(); } if (stream != null) { stream.Close(); } if (gstream != null) { gstream.Close(); } for (int i = 1; i < lines.Length; i++) { string[] infos = lines[i].Split('\t'); if (infos.Length < 3) { continue; } string fileName = infos[0].ToLower() == BundleConfig.mainManifestFile.ToLower() ? infos[0] : infos[0].ToLower(); mStreamBundleList.Add(fileName); } }