Dispose() 보호된 메소드

protected Dispose ( bool disposing ) : void
disposing bool
리턴 void
예제 #1
0
        /// <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;
            }
        }
예제 #2
0
 /// <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 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();
        }
예제 #4
0
        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;
        }
        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;
            }
        }
예제 #6
0
        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());
        }
예제 #7
0
파일: GzipUtils.cs 프로젝트: rongxiong/Scut
        /// <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 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();
        }
예제 #9
0
        /// <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);
        }
 /// <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;
 }
예제 #11
0
    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();
        }
    }
예제 #12
0
        public async Task<SerializerParameters> SerializeAsync(object value, Stream stream, CancellationToken cancellationToken = new CancellationToken())
        {
            if (value == null) throw new ArgumentNullException(nameof(value));
            if (stream == null) throw new ArgumentNullException(nameof(stream));

            Stream innerStream = stream;
            string contentEncoding = null;
            switch (Algorithm)
            {
                case CompressAlgorithm.Identity:
                    break;
                case CompressAlgorithm.Deflate:
                    innerStream = new DeflateStream(stream, CompressionLevel, true);
                    contentEncoding = "deflate";
                    break;
                case CompressAlgorithm.GZip:
                    innerStream = new GZipStream(stream, CompressionLevel, true);
                    contentEncoding = "gzip";
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(Algorithm));
            }
            try
            {
                var parameters = await InnerSerializer.SerializeAsync(value, innerStream, cancellationToken);

                return new SerializerParameters(parameters.ContentType, contentEncoding);
            }
            finally
            {
                if (innerStream != stream)
                    innerStream.Dispose();
            }
        }
예제 #13
0
        /// <summary>
        /// Decompresses stream using GZip. Returns decompressed Stream.
        /// Returns null if stream isn't compressed.
        /// </summary>
        /// <param name="compressedStream">Stream compressed with GZip.</param>
        public static MemoryStream DecompressStream(Stream compressedStream)
        {
            MemoryStream newStream = new MemoryStream();
            compressedStream.Seek(0, SeekOrigin.Begin);

            GZipStream Decompressor = null;
            try
            {
                Decompressor = new GZipStream(compressedStream, CompressionMode.Decompress, true);
                Decompressor.CopyTo(newStream);
            }
            catch (InvalidDataException invdata)
            {
                return null;
            }
            catch(Exception e)
            {
                throw;
            }
            finally
            {
                if (Decompressor != null)
                    Decompressor.Dispose();
            }

            return newStream;
        }
예제 #14
0
 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);
 }
예제 #15
0
파일: gZip.cs 프로젝트: aromero78/Total-CMS
        public static string Decompress(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();
        }
예제 #16
0
 public static string GetTextForGzip(Stream stream, Encoding coding)
 {
     GZipStream gzip = new GZipStream(stream, CompressionMode.Decompress);
     StreamReader reader = new StreamReader(gzip, coding);
     string html = reader.ReadToEnd();
     gzip.Close();
     gzip.Dispose();
     return html;
 }
예제 #17
0
        public static void CompressCanWrite()
        {
            var ms = new MemoryStream();
            var zip = new GZipStream(ms, CompressionMode.Compress);
            Assert.True(zip.CanWrite, "GZipStream not CanWrite with CompressionMode.Compress");

            zip.Dispose();
            Assert.False(zip.CanWrite, "GZipStream CanWrite after dispose");
        }
        public override void Write(long pageAddr, byte[] buf) 
        {
            long pageOffs = 0;
            if (pageAddr != 0) 
            { 
                Debug.Assert(buf.Length == Page.pageSize);
                Debug.Assert((pageAddr & (Page.pageSize-1)) == 0);
                long pagePos = pageMap.get(pageAddr);
                bool firstUpdate = false;
                if (pagePos == 0) 
                { 
                    long bp = (pageAddr >> (Page.pageSizeLog - 3));
                    byte[] posBuf = new byte[8];
                    indexFile.Read(bp, posBuf);
                    pagePos = Bytes.unpack8(posBuf, 0);
                    firstUpdate = true;
                }
                int pageSize = ((int)pagePos & (Page.pageSize-1)) + 1;
                MemoryStream ms = new MemoryStream();
                GZipStream stream = new GZipStream(ms, CompressionMode.Compress, true);
                stream.Write(buf, 0, buf.Length);
#if WINRT_NET_FRAMEWORK
                stream.Dispose();
#else
                stream.Close();
#endif
                if (ms.Length < Page.pageSize)
                {
                    buf = ms.ToArray();
                } 
                else 
                {
                    byte[] copy = new byte[buf.Length];
                    Array.Copy(buf, 0, copy, 0, buf.Length);
                }
                crypt(buf, buf.Length);
                int newPageBitSize = (buf.Length + ALLOCATION_QUANTUM - 1) >> ALLOCATION_QUANTUM_LOG;
                int oldPageBitSize = (pageSize + ALLOCATION_QUANTUM - 1) >> ALLOCATION_QUANTUM_LOG;

                if (firstUpdate || newPageBitSize != oldPageBitSize) 
                { 
                    if (!firstUpdate) 
                    { 
                        Bitmap.free(bitmap, pagePos >> (Page.pageSizeLog + ALLOCATION_QUANTUM_LOG), 
                                    oldPageBitSize);   
                    }
                    pageOffs = allocate(newPageBitSize);
                } 
                else 
                {
                    pageOffs = pagePos >> Page.pageSizeLog;
                }
                pageMap.put(pageAddr, (pageOffs << Page.pageSizeLog) | (buf.Length-1), pagePos);
            }
            base.Write(pageOffs, buf);
        }
예제 #19
0
        public static void DecompressCanRead()
        {
            var ms = new MemoryStream();
            var zip = new GZipStream(ms, CompressionMode.Decompress);

            Assert.True(zip.CanRead, "GZipStream not CanRead in Decompress");

            zip.Dispose();
            Assert.False(zip.CanRead, "GZipStream CanRead after dispose in Decompress");
        }
예제 #20
0
        public static void CanDisposeGZipStream()
        {
            var ms = new MemoryStream();
            var zip = new GZipStream(ms, CompressionMode.Compress);
            zip.Dispose();

            Assert.Null(zip.BaseStream);

            zip.Dispose(); // Should be a no-op
        }
예제 #21
0
 /// <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.Dispose();
             return(ms.ToArray());
         }
 }
        public string DecompressBytes(byte[] compressedByte)
        {
            // for holding decompressed byte
            string result;

            //Prepare for decompress
            MemoryStream ms = new MemoryStream(compressedByte);
            GZipStream compressor = new GZipStream(ms, CompressionMode.Decompress);

            //Reset variable to collect uncompressed result
            compressedByte = new byte[9999999];

            //Decompress and rByte is size of decompressed stream
            int rByte = compressor.Read(compressedByte, 0, compressedByte.Length);

            //CompressedByte is now decompressed
            MemoryStream decompressedStream = new MemoryStream(compressedByte);

            //converting to string to return
            StreamWriter writer = new StreamWriter(decompressedStream);
            writer.Write(compressedByte);
            writer.Flush();

            decompressedStream.Position = 0;
            StreamReader reader = new StreamReader(decompressedStream);
            result = reader.ReadToEnd();

            //XXXXXXXXX: TextBlockSize.Text = result.Length.ToString()+" B"; //This gives size of decompressedStream which is 9999999
            //******TextBlockAnsSize.Text = rByte.ToString() + " B";

            // Cleanup if they are to be used again
            compressor.Dispose();

            return result;

            ////Uncomment these if you want to use String instead of string (Some modification have to be done may be)

            ////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)compressedByte[i]);
            //}

            //compressor.Dispose();
            //ms.Dispose();
            //TextBlockAnsSize.Text = sB.Length.ToString()+" B";

            //return sB.ToString();

        }
예제 #23
0
파일: Utils.cs 프로젝트: GammaForce/Updater
 /// <summary>
 /// Returns a decompressed byte array of a file compressed with GZip
 /// </summary>
 /// <param name="Input">Compressed file bytes</param>
 /// <returns>Decompressed file bytes</returns>
 /// <remarks>Find a better compression system?</remarks>
 public static byte[] Decompress(byte[] Input)
 {
     MemoryStream InputMS = new MemoryStream(Input);
     MemoryStream OutputMS = new MemoryStream();
     using (GZipStream GZip = new GZipStream(InputMS, CompressionMode.Decompress))
     {
         GZip.CopyTo(OutputMS);
         GZip.Dispose();
     }
     return OutputMS.ToArray();
 }
예제 #24
0
 public static byte[] CompressToSelf(object o)
 {
     byte[] buffer = ObjectToByteArrayToSelf(o);
     MemoryStream stream = new MemoryStream();
     GZipStream stream2 = new GZipStream(stream, CompressionMode.Compress, true);
     stream2.Write(buffer, 0, buffer.Length);
     stream2.Close();
     stream2.Dispose();
     byte[] buffer2 = stream.ToArray();
     stream.Close();
     stream.Dispose();
     return buffer2;
 }
예제 #25
0
 /// <summary>
 /// GZip压缩函数
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static byte[] GZipCompress(byte[] data)
 {
     using (MemoryStream stream = new MemoryStream())
     {
         using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress))
         {
             gZipStream.Write(data, 0, data.Length);
             gZipStream.Close();
             gZipStream.Dispose();
         }
         return stream.ToArray();
     }
 }
예제 #26
0
 static void GzipStream()
 {
     System.IO.FileStream             newFileStream = new System.IO.FileStream("compressed.gz", System.IO.FileMode.Create);
     System.IO.Compression.GZipStream gZipStream    =
         new System.IO.Compression.GZipStream(newFileStream, System.IO.Compression.CompressionLevel.Fastest);
     byte[] bytes = System.Text.Encoding.Unicode.GetBytes("This is some text that will be compressed");
     gZipStream.Write(bytes, 0, bytes.Length);
     gZipStream.Dispose();
     System.IO.Compression.GZipStream decompressStream =
         new System.IO.Compression.GZipStream(System.IO.File.OpenRead("compressed.gz"), System.IO.Compression.CompressionMode.Decompress);
     System.IO.StreamReader streamReader = new System.IO.StreamReader(decompressStream, System.Text.Encoding.Unicode);
     System.Console.WriteLine(streamReader.ReadToEnd());
 }
 public static byte[] GZipDecompress(byte[] data)
 {
     //Console.WriteLine("GZipDecompress");
     MemoryStream ms = new MemoryStream(data);
     GZipStream stream = new GZipStream(ms, CompressionMode.Decompress);
     byte[] buffer = StreamDataHelper.ReadDataToBytes(stream);
     ms.Close();
     ms.Dispose();
     ms = null;
     stream.Close();
     stream.Dispose();
     stream = null;
     return buffer;
 }
예제 #28
0
 public static byte[] GZip(this byte[] bytes)
 {
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     GZipStream gs = new GZipStream(ms, CompressionMode.Compress, true);
     gs.Write(bytes, 0, bytes.Length);
     gs.Close();
     gs.Dispose();
     ms.Position = 0;
     bytes = new byte[ms.Length];
     ms.Read(bytes, 0, (int)ms.Length);
     ms.Close();
     ms.Dispose();
     return bytes;
 }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                               CancellationToken cancellationToken)
        {
            HttpResponseMessage response;
            // Handle only if content type is 'application/gzip'
            var contentEncoding = request.Content.Headers.ContentEncoding.FirstOrDefault();
            if (contentEncoding == null ||
                contentEncoding.Contains("gzip") == false)
            {
                response = await base.SendAsync(request, cancellationToken);
                return Compress(response);
            }

            // Read in the input stream, then decompress in to the output stream.
            // Doing this asynchronously, but not really required at this point
            // since we end up waiting on it right after this.
            Stream outputStream = new MemoryStream();
            await request.Content.ReadAsStreamAsync().ContinueWith(t =>
            {
                Stream inputStream = t.Result;
                var gzipStream = new GZipStream(inputStream, CompressionMode.Decompress);

                CopyBetween(gzipStream, outputStream);
                
                gzipStream.Dispose();

                outputStream.Seek(0, SeekOrigin.Begin);
            }, cancellationToken);

            // This next section is the key...

            // Save the original content
            HttpContent origContent = request.Content;

            // Replace request content with the newly decompressed stream
            request.Content = new StreamContent(outputStream);

            // Copy all headers from original content in to new one
            foreach (var header in origContent.Headers)
            {
                foreach (var val in header.Value)
                {
                    request.Content.Headers.Add(header.Key, val);
                }
            }

            response = await base.SendAsync(request, cancellationToken);
            return Compress(response);
        }
 public static byte[] GZipCompress(byte[] DATA)
 {
     //Console.WriteLine("GZipCompress");
     MemoryStream ms = new MemoryStream();
     GZipStream stream = new GZipStream(ms, CompressionMode.Compress, true);
     stream.Write(DATA, 0, DATA.Length);
     stream.Close();
     stream.Dispose();
     stream = null;
     byte[] buffer = StreamDataHelper.ReadDataToBytes(ms);
     ms.Close();
     ms.Dispose();
     ms = null;
     return buffer;
 }
 public static Stream GZipCompress(Stream DATA)
 {
     Console.WriteLine("GZipCompress");
     byte[] buffer = StreamDataHelper.ReadDataToBytes(DATA);
     MemoryStream ms = new MemoryStream();
     GZipStream stream = new GZipStream(ms, CompressionMode.Compress, true);
     stream.Write(buffer, 0, buffer.Length);
     stream.Close();
     stream.Dispose();
     stream = null;
     if (ms.CanSeek)
     {
         ms.Position = 0;
     }
     return ms;
 }
예제 #32
0
파일: Settings.cs 프로젝트: coodream/cms
        static Settings()
        {

            //检测是否支持开启GZIP
            try
            {
                MemoryStream ms = new MemoryStream();
                GZipStream gs = new GZipStream(ms, CompressionMode.Compress);
                gs.Dispose();
                ms.Dispose();
                Settings.Opti_SupportGZip = true;
            }
            catch
            {
                Settings.Opti_SupportGZip = false;
            }
        }
예제 #33
0
    // **********************************************************************

    public static Stream GetDataStream(FileStream fs)
    {
      byte[] buffer = new byte[prefix.Length];

      if(CheckPrefix(fs, buffer))
        return fs;

      Stream stream = null;

      try
      {
        fs.Position = 0;
        stream = new GZipStream(fs, CompressionMode.Decompress, true);

        if(CheckPrefix(stream, buffer))
          return stream;
      }
      catch { }

      if(stream != null)
      {
        stream.Dispose();
        stream = null;
      }

      try
      {
        fs.Position = 0;
        stream = new DeflateStream(fs, CompressionMode.Decompress, true);

        if(CheckPrefix(stream, buffer))
          return stream;
      }
      catch { }

      if(stream != null)
      {
        stream.Dispose();
        stream = null;
      }

      throw new FormatException("Неверный формат файла");
    }
예제 #34
0
 private static void Assemble(List<string> files, string destinationDirectory,string extension)
 {
     FileStream writer = new FileStream(destinationDirectory + "assembled" + "." + extension,FileMode.Create);
     for (int i = 0; i < files.Count; i++)
     {
         FileStream reader = new FileStream(destinationDirectory + files[i],FileMode.Open,FileAccess.ReadWrite);
         GZipStream readerGzip = new GZipStream(reader,CompressionMode.Decompress);
         int readBytesVariable = readerGzip.ReadByte();
         while (readBytesVariable != -1)
         {
             writer.WriteByte((byte)readBytesVariable);
             readBytesVariable = readerGzip.ReadByte();
         }
         readerGzip.Dispose();
         reader.Dispose();
     }
     writer.Flush();
     writer.Dispose();
 }
예제 #35
0
 protected override void Process(FileInfo inputFile, FileInfo outputFile)
 {
     using (FileStream inputStream = inputFile.OpenRead(), outputStream = outputFile.OpenWrite())
     {
         var zipStream = new GZipStream(outputStream, CompressionMode.Compress);
         var buffer = new byte[_bufferSize];
         var bytesRead = 0;
         while ((bytesRead = inputStream.Read(buffer, 0, _bufferSize)) > 0)
         {
             if ((inputStream.Position + _bufferSize) % MaxBlockSize > MaxBlockSize)
             {
                 zipStream.Dispose();
                 zipStream = new GZipStream(outputStream, CompressionMode.Compress);
             }
             zipStream.Write(buffer, 0, bytesRead);
         }
         zipStream.Dispose();
     }
 }
        /// <summary>
        /// 序列化压缩
        /// </summary>
        /// <param name="obj">需要压缩的对象</param>
        /// <returns>Byte[]</returns>
        public static byte[] Serializer(object obj)
        {
            IFormatter formatter = new BinaryFormatter();//定义BinaryFormatter以序列化object对象
            MemoryStream ms = new MemoryStream();//创建内存流对象
            formatter.Serialize(ms, obj);//把object对象序列化到内存流
            byte[] buffer = ms.ToArray();//把内存流对象写入字节数组
            ms.Close();//关闭内存流对象
            ms.Dispose();//释放资源
            MemoryStream msNew = new MemoryStream();
            GZipStream gzipStream = new GZipStream(msNew, CompressionMode.Compress, true);//创建压缩对象
            gzipStream.Write(buffer, 0, buffer.Length);//把压缩后的数据写入文件
            gzipStream.Close();//关闭压缩流,这里要注意:一定要关闭,要不然解压缩的时候会出现小于4K的文件读取不到数据,大于4K的文件读取不完整
            gzipStream.Dispose();//释放对象

            var bufferNew = msNew.ToArray();

            msNew.Close();
            msNew.Dispose();
            return bufferNew;
        }
예제 #37
0
파일: GZipUtil.cs 프로젝트: radtek/CoinsPro
        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());
        }
예제 #38
0
    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());
    }
예제 #39
0
        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());
        }
예제 #40
0
        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);
        }