コード例 #1
0
 public override void Close()
 {
     if (!initdone)
     {
         doInit();                         // can happen if never called write
     }
     if (closed)
     {
         return;
     }
     closed = true;
     if (deflateStream != null)
     {
         deflateStream.Close();
     }
     if (crcread == null)
     {             // eat trailing 4 bytes
         crcread = new byte[4];
         for (int i = 0; i < 4; i++)
         {
             crcread[i] = (byte)rawStream.ReadByte();
         }
     }
     if (!leaveOpen)
     {
         rawStream.Close();
     }
 }
コード例 #2
0
ファイル: IOHelper.cs プロジェクト: windygu/asxinyunet
 /// <summary>
 /// 压缩
 /// </summary>
 /// <param name="inStream">输入流</param>
 /// <param name="outStream">输出流</param>
 public static void Compress(this Stream inStream, Stream outStream)
 {
     Stream stream = new DeflateStream(outStream, CompressionMode.Compress, true);
     CopyTo(inStream, stream);
     stream.Flush();
     stream.Close();
 }
コード例 #3
0
ファイル: Script_Crypt.cs プロジェクト: stephenZh/l2net
        public static StreamReader Decrypt(string source, int key)
        {
            byte[] data = System.Convert.FromBase64String(source);

            byte[] dec = AES.DecryptData(data, GetTrueKey(key), key.ToString() + "P8xvDLzPHvNiwVMkS3kPzQStAEDqdTMD", System.Security.Cryptography.PaddingMode.ISO10126);

            int d_len = System.BitConverter.ToInt32(dec, 40);

            MemoryStream ms = new MemoryStream(dec);
            ms.Position = 44;
            // Use the newly created memory stream for the compressed data.
            DeflateStream compressedzipStream = new DeflateStream(ms, CompressionMode.Decompress, true);
            //Console.WriteLine("Compression");
            byte[] zdec = new byte[d_len];
            int cnt = compressedzipStream.Read(zdec, 0, d_len);
            // Close the stream.
            compressedzipStream.Close();

            dec = new byte[cnt];
            System.Array.ConstrainedCopy(zdec, 0, dec, 0, cnt);

            MemoryStream mem_stream = new System.IO.MemoryStream(dec);
            StreamReader output = new System.IO.StreamReader((System.IO.Stream)mem_stream);

            return output;
        }
コード例 #4
0
ファイル: ArchivePacker.cs プロジェクト: stsuper/TTG_Tools
 private static byte[] DeflateCompressor(byte[] bytes) //Для старых (версии 8 и 9) и новых архивов
 {
     byte[] retVal;
     using (MemoryStream compressedMemoryStream = new MemoryStream())
     {
         System.IO.Compression.DeflateStream compressStream = new System.IO.Compression.DeflateStream(compressedMemoryStream, System.IO.Compression.CompressionMode.Compress, true);
         compressStream.Write(bytes, 0, bytes.Length);
         compressStream.Close();
         retVal = new byte[compressedMemoryStream.Length];
         compressedMemoryStream.Position = 0L;
         compressedMemoryStream.Read(retVal, 0, retVal.Length);
         compressedMemoryStream.Close();
         compressStream.Close();
     }
     return(retVal);
 }
コード例 #5
0
ファイル: Compression.cs プロジェクト: VincentRisi/jportal
 public static byte[] Compress(string data)
 {
     byte[] input = Encoding.ASCII.GetBytes(data);
       MemoryStream ms = new MemoryStream();
       DeflateStream zipper = new DeflateStream(ms, CompressionMode.Compress, true);
       zipper.Write(input, 0, input.Length);
       zipper.Close();
       byte[] output;
       if (ms.Length < input.Length)
       {
     output = new byte[ms.Length + 8];
     SetLength(input.Length, output, 0);
     SetLength((int)ms.Length, output, 4);
     ms.Position = 0;
     ms.Read(output, 8, output.Length - 8);
       }
       else
       {
     output = new byte[input.Length + 8];
     SetLength(input.Length, output, 0);
     SetLength(input.Length, output, 4);
     input.CopyTo(output, 8);
       }
       return output;
 }
コード例 #6
0
ファイル: DataGetterTest.cs プロジェクト: ttu/scratchpad
        public void CompressTest()
        {
            var s = "StartTime:13.4.201213:15:26;RunTime:00:01:24";

            var ms = new MemoryStream();
            var ds = new DeflateStream(ms, CompressionMode.Compress);

            var encoding = System.Text.Encoding.UTF8;
            var byteData = encoding.GetBytes(s);

            Trace.WriteLine("original    : {0}", s);
            ds.Write(byteData, 0, byteData.Length);
            ds.Close();
            byte[] compressed = ms.ToArray();

            Trace.WriteLine("compressed  : {0}", System.Convert.ToBase64String(compressed));

            ms = new MemoryStream(compressed);
            ds = new DeflateStream(ms, CompressionMode.Decompress);
            compressed = new byte[compressed.Length + 100];
            var offset = 0;

            while (true)
            {
                int bytesRead = ds.Read(compressed, offset, 1);
                if (bytesRead == 0) { break; }
                offset += bytesRead;
            }

            ds.Close();

            string uncompressed = encoding.GetString(compressed);

            Trace.WriteLine("uncompressed: {0}\n", uncompressed);
        }
コード例 #7
0
ファイル: ZLibHelper.cs プロジェクト: Translator5/TuxLoL
        public static byte[] Compress(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            using (var output = new MemoryStream())
            {
                // ZLib Header 0x78 0x9C
                output.WriteByte(0x78);
                output.WriteByte(0x9C);
                using (var input = new MemoryStream(data))
                {
                    using (var compressionStream = new DeflateStream(output, CompressionMode.Compress, true))
                    {
                        input.CopyTo(compressionStream);
                        compressionStream.Close();

                        // Adler32 hash of the uncompressed data
                        var adler32 = new Adler32();
                        adler32.Update(data);
                        byte[] hash = BitConverter.GetBytes((int) adler32.Value);
                        Array.Reverse(hash);
                        output.Write(hash, 0, hash.Length);
                        return output.ToArray();
                    }
                }
            }
        }
コード例 #8
0
        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();
            }

        }
コード例 #9
0
        /// <summary>
        /// Get EditorsTable from server response.
        /// </summary>
        /// <param name="subResponse">The sub response from server.</param>
        /// <param name="site">Transfer ITestSite into this operation, for this operation to use ITestSite's function.</param>
        /// <returns>The instance of EditorsTable.</returns>
        public static EditorsTable GetEditorsTableFromResponse(FsshttpbResponse subResponse, ITestSite site)
        {
            if (subResponse == null || subResponse.DataElementPackage == null || subResponse.DataElementPackage.DataElements == null)
            {
                site.Assert.Fail("The parameter CellResponse is not valid, check whether the CellResponse::DataElementPackage or CellResponse::DataElementPackage::DataElements is null.");
            }

            foreach (DataElement de in subResponse.DataElementPackage.DataElements)
            {
                if (de.Data.GetType() == typeof(ObjectGroupDataElementData))
                {
                    ObjectGroupDataElementData ogde = de.Data as ObjectGroupDataElementData;

                    if (ogde.ObjectGroupData == null || ogde.ObjectGroupData.ObjectGroupObjectDataList.Count == 0)
                    {
                        continue;
                    }

                    for (int i = 0; i < ogde.ObjectGroupData.ObjectGroupObjectDataList.Count; i++)
                    {
                        if (IsEditorsTableHeader(ogde.ObjectGroupData.ObjectGroupObjectDataList[i].Data.Content.ToArray()))
                        {
                            string editorsTableXml = null;

                            // If the current object group object data is the header byte array 0x1a, 0x5a, 0x3a, 0x30, 0, 0, 0, 0, then the immediate following object group object data will contain the Editor table xml. 
                            byte[] buffer = ogde.ObjectGroupData.ObjectGroupObjectDataList[i + 1].Data.Content.ToArray();
                            System.IO.MemoryStream ms = null;
                            try
                            {
                                ms = new System.IO.MemoryStream();
                                ms.Write(buffer, 0, buffer.Length);
                                ms.Position = 0;
                                using (DeflateStream stream = new DeflateStream(ms, CompressionMode.Decompress))
                                {
                                    stream.Flush();
                                    byte[] decompressBuffer = new byte[buffer.Length * 3];
                                    stream.Read(decompressBuffer, 0, buffer.Length * 3);
                                    stream.Close();
                                    editorsTableXml = System.Text.Encoding.UTF8.GetString(decompressBuffer);
                                }

                                ms.Close();
                            }
                            finally
                            {
                                if (ms != null)
                                {
                                    ms.Dispose();
                                }
                            }

                            return GetEditorsTable(editorsTableXml);
                        }
                    }
                }
            }

            throw new InvalidOperationException("Cannot find any data group object data contain editor tables information.");
        }
コード例 #10
0
 /// <summary>
 ///		Compresses a data buffer using a simple huffman deflate algorithem.
 /// </summary>
 /// <param name="data">Data buffer to compress.</param>
 /// <returns>Compressed version of data buffer.</returns>
 public static byte[] Deflate(byte[] data)
 {
     MemoryStream memoryStream = new MemoryStream();
     DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress, true);
     deflateStream.Write(data, 0, data.Length);
     deflateStream.Close();
     return memoryStream.ToArray();
 }
コード例 #11
0
 /// <summary>
 /// Decompresses the specified input.
 /// </summary>
 /// <param name="input">The input.</param>
 /// <returns>The decompressed data.</returns>
 public static byte[] Decompress(this byte[] input)
 {
     var inflatedStream = new MemoryStream(input);
     var outputStream = new MemoryStream();
     var decompressor = new DeflateStream(inflatedStream, CompressionMode.Decompress);
     decompressor.CopyTo(outputStream);
     decompressor.Close();
     return outputStream.ToArray();
 }
コード例 #12
0
 /// <summary>
 /// Compresses the specified input.
 /// </summary>
 /// <param name="input">The input.</param>
 /// <returns>The compressed data.</returns>
 public static byte[] Compress(this byte[] input)
 {
     var inputStream = new MemoryStream(input);
     var outputStream = new MemoryStream();
     var compressor = new DeflateStream(outputStream, CompressionMode.Compress);
     inputStream.CopyTo(compressor);
     compressor.Close();
     return outputStream.ToArray();
 }
コード例 #13
0
ファイル: ByteArrays.cs プロジェクト: Azerothian/Empire
 /// <summary>
 /// Compresses the specified data.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <returns></returns>
 public static byte[] Compress(byte[] data)
 {
     MemoryStream ms = new MemoryStream();
     DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Write(data, 0, data.Length);
     ds.Flush();
     ds.Close();
     return ms.ToArray();
 }
コード例 #14
0
ファイル: IOHelper.cs プロジェクト: g992com/esb
 /// <summary>解压缩数据流</summary>
 /// <param name="inStream">输入流</param>
 /// <param name="outStream">输出流</param>
 public static void Decompress(this Stream inStream, Stream outStream)
 {
     // 第三个参数为true,保持数据流打开,内部不应该干涉外部,不要关闭外部的数据流
     using (Stream stream = new DeflateStream(inStream, CompressionMode.Decompress, true))
     {
         stream.CopyTo(outStream);
         stream.Close();
     }
 }
コード例 #15
0
ファイル: ZLib.cs プロジェクト: WoWServer/WoWServer
 public static byte[] Compress(byte[] data)
 {
     using (var compressedStream = new MemoryStream())
     using (var zipStream = new DeflateStream(compressedStream, CompressionMode.Compress))
     {
         zipStream.Write(data, 0, data.Length);
         zipStream.Close();
         return compressedStream.ToArray();
     }
 }
コード例 #16
0
ファイル: Compressor.cs プロジェクト: DacoTaco/AudioStreaming
        public static byte[] Compress(byte[] data)
        {
            var memoryStream = new MemoryStream();
            var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress);
            deflateStream.Write(data, 0, data.Length);
            deflateStream.Flush();
            deflateStream.Close();

            return memoryStream.ToArray();
        }
コード例 #17
0
ファイル: FlateFilter.cs プロジェクト: nholik/Fo.Net
 public byte[] Encode(byte[] data)
 {
     MemoryStream ms = new MemoryStream(data.Length);
     ms.WriteByte(0x78); // ZLib Header for compression level 3.
     ms.WriteByte(0x5e);
     DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);
     ds.Write(data, 0, data.Length);
     ds.Close();
     return ms.ToArray();
 }
コード例 #18
0
ファイル: DeflateEncoder.cs プロジェクト: JacoRuit/Lugubris
 public byte[] Encode(byte[] data)
 {
     var output = new MemoryStream();
     var gzipstream = new DeflateStream(output, CompressionMode.Compress);
     gzipstream.Write(data, 0, data.Length);
     gzipstream.Close();
     byte[] compressed = output.ToArray();
     output.Close();
     return compressed;
 }
コード例 #19
0
        /// <summary>
        /// Decompresses data.
        /// </summary>
        public static byte[] DecompressData(byte[] data, int decompressedLength)
        {
            var dataStream = new MemoryStream(data);
            var deflateStream = new DeflateStream(dataStream, CompressionMode.Decompress);

            var buffer = new byte[decompressedLength];
            deflateStream.Read(buffer, 0, decompressedLength);
            deflateStream.Close();

            return buffer;
        }
コード例 #20
0
ファイル: Utility.cs プロジェクト: frostmourne/toms_tools
        public static byte[] Decompress(byte[] data)
        {
            var uncompressedLength = BitConverter.ToUInt32(data, 0);
            var output = new byte[uncompressedLength];

            var dStream = new DeflateStream(new MemoryStream(data, 6, data.Length - 6), CompressionMode.Decompress);
            dStream.Read(output, 0, output.Length);
            dStream.Close();

            return output;
        }
コード例 #21
0
 internal static byte[] Compress(byte[] data)
 {
     using (var ms = new MemoryStream())
     {
         var ds = new DeflateStream(ms, CompressionMode.Compress);
         ds.Write(data, 0, data.Length);
         ds.Flush();
         ds.Close();
         return ms.ToArray();
     }
 }
コード例 #22
0
ファイル: OutputRMState.cs プロジェクト: mbmccormick/Ximura
        /// <summary>
        /// This method prepares the binary body for output from the content.
        /// </summary>
        /// <param name="context">The current context.</param>
        /// <param name="content">The content to be prepared.</param>
        /// <returns>Returns a ResourceManagerMessageFragmentBody object with the binary representation of the content.</returns>
        protected virtual ResourceManagerMessageFragmentBody PrepareBodyOutput(ResourceManagerContext context, BinaryContent content)
        {
            ResourceManagerMessageFragmentBody
                body = context.GetObjectPool<ResourceManagerMessageFragmentBody>().Get();

            byte[] blob = content.ToArray();

            switch (context.Request.Data.RequestPreferredCompression)
            {
                case "gzip":
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (Stream gz = new GZipStream(ms, CompressionMode.Compress, true))
                        {
                            gz.Write(blob, 0, blob.Length);
                            gz.Close();
                        }
                        ms.Position = 0;
                        body.Load(ms);
                    }
                    body.ContentEncoding = "gzip";
                    break;
                case "deflate":
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (Stream gz = new DeflateStream(ms, CompressionMode.Compress, true))
                        {
                            gz.Write(blob, 0, blob.Length);
                            gz.Close();
                        }
                        ms.Position = 0;
                        body.Load(ms);
                    }
                    body.ContentEncoding = "deflate";
                    break;
                default:
                    body.Load(blob, 0, blob.Length);
                    break;
            }

            blob = null;

            if (content.MimeType == null || content.MimeType == "")
            {
                if (context.Request.Settings.OutputColl.Count > 0)
                    body.ContentType = context.Request.Settings.OutputColl[0].OutputMIMEType;
                else
                    body.ContentType = "application/octet-stream";
            }
            else
                body.ContentType = content.MimeType;

            return body;
        }
コード例 #23
0
 /// <summary>
 /// Compresses the given data.
 /// </summary>
 /// <param name="data">The data to compress.</param>
 /// <returns>The compressed version of the data.</returns>
 public static byte[] Compress(byte[] data)
 {
     using (var streamData = new MemoryStream(data))
     using (var streamCompressed = new MemoryStream())
     using (var deflate = new DeflateStream(streamCompressed, CompressionMode.Compress))
     {
         streamData.CopyTo(deflate);
         deflate.Close();
         return streamCompressed.ToArray();
     }
 }
コード例 #24
0
        public byte[] Deflate(string text)
        {
            var buffer = Encoding.UTF8.GetBytes(text);
            using(var ms = new MemoryStream())
            using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
            {
                zipStream.Write(buffer, 0, buffer.Length);
                zipStream.Close();

                return ms.ToArray();
            }
        }
コード例 #25
0
ファイル: Deflate.cs プロジェクト: pengyancai/cs-util
 /// <summary>
 /// Compresses data
 /// </summary>
 /// <param name="Bytes">The byte array to be compressed</param>
 /// <returns>A byte array of compressed data</returns>
 public static byte[] Compress(byte[] Bytes)
 {
     using (MemoryStream Stream = new MemoryStream())
     {
         using (DeflateStream ZipStream = new DeflateStream(Stream, CompressionMode.Compress, true))
         {
             ZipStream.Write(Bytes, 0, Bytes.Length);
             ZipStream.Close();
             return Stream.ToArray();
         }
     }
 }
コード例 #26
0
ファイル: Compressor.cs プロジェクト: ZiadJ/Univar
 public static string CompressToBinary(object obj)
 {
     MemoryStream ms = new MemoryStream();
     new BinaryFormatter().Serialize(ms, obj);
     byte[] inbyt = ms.ToArray();
     MemoryStream objStream = new MemoryStream();
     DeflateStream objZS = new DeflateStream(objStream, CompressionMode.Compress);
     objZS.Write(inbyt, 0, inbyt.Length);
     objZS.Flush();
     objZS.Close();
     return Convert.ToBase64String(objStream.ToArray());
 }
コード例 #27
0
        /// <summary>
        /// 提供内部使用,解压缩字流的方法
        /// </summary>
        public static byte[] Decompress(byte[] data)
        {
            DeflateStream zip = null;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(data, 0, data.Length);
                    ms.Flush();
                    ms.Position = 0;
                    zip = new DeflateStream(ms, CompressionMode.Decompress, true);
                    using (MemoryStream os = new MemoryStream())
                    {
                        int SIZE = 1024;
                        byte[] buf = new byte[SIZE];
                        int l = 0;
                        do
                        {
                            l = zip.Read(buf, 0, SIZE);
                            if (l == 0) l = zip.Read(buf, 0, SIZE);
                            os.Write(buf, 0, l);
                        } while (l != 0);
                        byte[] bs = os.ToArray();

                        os.Close();
                        zip.Close();

                        return bs;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("解压缩流发生异常 - " + ex.Message, ex);
            }
            finally
            {
                if (zip != null) zip.Close();
            }
        }
コード例 #28
0
 /// <summary>
 /// Compresses binary data with Deflate method.
 /// </summary>
 /// <param name="Data">Byte array with data to compress.</param>
 /// <returns>Returns the result byte array with compressed data if successful, otherwise returns NULL.</returns>
 public static byte[] CompressData(byte[] Data)
 {
     try
     {
         var MS = new MemoryStream();
         var CS = new DeflateStream(MS, CompressionMode.Compress, true);
         CS.Write(Data, 0, Data.Length);
         CS.Flush();
         CS.Close();
         return MS.ToArray();
     }
     catch	{	return null;	}
 }
コード例 #29
0
 /// <summary>
 /// Compresses a byte array through Deflate
 /// </summary>
 /// <param name="data">Data to compress</param>
 /// <returns>Compressed data</returns>
 public static byte[] Deflate(this byte[] data)
 {
     MemoryStream buffer = new MemoryStream();
     DeflateStream compressor = new DeflateStream(buffer, CompressionMode.Compress, true);
     compressor.Write(data, 0, data.Length);
     compressor.Close();
     buffer.Flush();
     buffer.Position = 0;
     byte[] output = new byte[buffer.Length];
     buffer.Read(output, 0, output.Length);
     buffer.Close();
     return output;
 }
コード例 #30
0
        public byte[] Deflate(byte[] bytes)
        {
            // In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
            // Which means we must use MemoryStream since you have to use ToArray() on a closed Stream
            using (var ms = new MemoryStream())
            using (var zipStream = new DeflateStream(ms, CompressionMode.Compress))
            {
                zipStream.Write(bytes, 0, bytes.Length);
                zipStream.Close();

                return ms.ToArray();
            }
        }
コード例 #31
0
ファイル: ZipObject.cs プロジェクト: kangwl/KANG.Frame
 public static byte[] CompressionObject(object DataOriginal) {
     if (DataOriginal == null) return null;
     var bFormatter = new BinaryFormatter();
     var mStream = new MemoryStream();
     bFormatter.Serialize(mStream, DataOriginal);
     var bytes = mStream.ToArray();
     var oStream = new MemoryStream();
     var zipStream = new DeflateStream(oStream, CompressionMode.Compress);
     zipStream.Write(bytes, 0, bytes.Length);
     zipStream.Flush();
     zipStream.Close();
     return oStream.ToArray();
 }
コード例 #32
0
        static void Main(string[] args)
        {
            string file;

            if (args.Length > 0) file = args[0];
            else
            {
                Console.Write("File: ");
                file = Console.ReadLine();
            }

            if (file == null || !File.Exists(file)) Environment.Exit(1);

            var input = new FileStream(file, FileMode.Open);
            var output = new FileStream(file + ".sd0", FileMode.Create);

            using (var writer = new BinaryWriter(output, Encoding.UTF8))
            {
                writer.Write('s');
                writer.Write('d');
                writer.Write('0');
                writer.Write((byte)0x01);
                writer.Write((byte)0xff);

                const int chunkMaxLength = 1024 * 256;

                int read;
                var buffer = new byte[chunkMaxLength];

                var chunkNumber = 1;

                while ((read = input.Read(buffer, 0, chunkMaxLength)) > 0)
                {
                    Console.WriteLine("Writing chunk {0}...", chunkNumber);
                    using (var outputStream = new MemoryStream())
                    using (var compressionStream = new DeflateStream(outputStream, CompressionMode.Compress, true))
                    {
                        compressionStream.Write(buffer, 0, read);
                        compressionStream.Flush();
                        compressionStream.Close();

                        writer.Write(outputStream.ToArray().Length);
                        writer.Write(outputStream.ToArray());
                    }
                    Console.WriteLine(" ->OK");
                    chunkNumber++;
                }

                Console.WriteLine("Done.");
            }
        }
コード例 #33
0
ファイル: CommonClass.cs プロジェクト: sahvishal/matrix
        public static byte[] CompressDataSet(DataSet ds)
        {
            ds.RemotingFormat = SerializationFormat.Binary;
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream    ms = new MemoryStream();

            bf.Serialize(ms, ds);
            byte[] inbyt = ms.ToArray();
            System.IO.MemoryStream objStream          = new MemoryStream();
            System.IO.Compression.DeflateStream objZS = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress);
            objZS.Write(inbyt, 0, inbyt.Length);
            objZS.Flush();
            objZS.Close();
            return(objStream.ToArray());
        }
コード例 #34
0
        public static string ZipBase64(string s)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream    ms = new MemoryStream();

            bf.Serialize(ms, s);
            byte[] inbyt = ms.ToArray();
            System.IO.MemoryStream objStream          = new MemoryStream();
            System.IO.Compression.DeflateStream objZS = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress);
            objZS.Write(inbyt, 0, inbyt.Length);
            objZS.Flush();
            objZS.Close();
            byte[] b             = objStream.ToArray();
            string ZippedBased64 = Convert.ToBase64String(b);

            return(ZippedBased64);
        }
コード例 #35
0
ファイル: CookieManager.cs プロジェクト: tuxevil/FashionAde
        public static bool Set(string cookieName, object cookieValue)
        {
            bool retval = true;

            try
            {
                BinaryFormatter bf = new BinaryFormatter();

                MemoryStream ms = new MemoryStream();

                bf.Serialize(ms, cookieValue);

                byte[] inbyt = ms.ToArray();

                System.IO.MemoryStream objStream = new MemoryStream();

                System.IO.Compression.DeflateStream objZS = new System.IO.Compression.DeflateStream(objStream, System.IO.Compression.CompressionMode.Compress);

                objZS.Write(inbyt, 0, inbyt.Length);

                objZS.Flush();

                objZS.Close();

                byte[] b = objStream.ToArray();

                string sCookieVal = Convert.ToBase64String(b);

                HttpCookie cook = new HttpCookie(cookieName);

                cook.Value = sCookieVal;

                cook.Expires = DateTime.Today.AddDays(30);

                HttpContext.Current.Response.Cookies.Add(cook);
            }

            catch
            {
                retval = false;

                throw;
            }

            return(retval);
        }
コード例 #36
0
 /// <summary>
 /// Deflate解压函数
 /// JS:var details = eval_r('(' + utf8to16(zip_depress(base64decode(hidEnCode.value))) + ')')对应的C#压缩方法
 /// </summary>
 /// <param name="strSource"></param>
 /// <returns></returns>
 public static string DeflateDecompress(this string strSource)
 {
     byte[] buffer = Convert.FromBase64String(strSource);
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         ms.Write(buffer, 0, buffer.Length);
         ms.Position = 0;
         using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress))
         {
             stream.Flush();
             int    nSize            = 16 * 1024 + 256; //假设字符串不会超过16K
             byte[] decompressBuffer = new byte[nSize];
             int    nSizeIncept      = stream.Read(decompressBuffer, 0, nSize);
             stream.Close();
             return(System.Text.Encoding.UTF8.GetString(decompressBuffer, 0, nSizeIncept));   //转换为普通的字符串
         }
     }
 }
コード例 #37
0
        public void testDeflateStream()
        {
            // make sure compression works, file should be smaller
            string sample = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files", "fp.log");

            byte[] uncompressed = File.ReadAllBytes(sample);
            int    before       = uncompressed.Length;

            byte[] compressed;
            int    after = 0;

            // test deflate stream compression code
            using (MemoryStream compressStream = new MemoryStream())
                using (ZopfliStream compressor = new ZopfliStream(compressStream, ZopfliFormat.ZOPFLI_FORMAT_DEFLATE))
                {
                    compressor.Write(uncompressed, 0, before);
                    compressor.Close();
                    compressed = compressStream.ToArray();
                    after      = compressed.Length;
                }

            before.Should().BeGreaterThan(after);

            // make sure we can decompress the file using built-in .net
            byte[] decompressedBytes = new byte[before];
            using (System.IO.Compression.DeflateStream decompressionStream = new System.IO.Compression.DeflateStream(new MemoryStream(compressed), System.IO.Compression.CompressionMode.Decompress))
            {
                decompressionStream.Read(decompressedBytes, 0, before);
            }
            uncompressed.Should().Equal(decompressedBytes);

            // use built-in .net compression and make sure zopfil is smaller
            int after_builtin = 0;

            using (MemoryStream compressStream = new MemoryStream())
                using (System.IO.Compression.DeflateStream compressor = new System.IO.Compression.DeflateStream(compressStream, System.IO.Compression.CompressionLevel.Optimal))
                {
                    compressor.Write(uncompressed, 0, before);
                    compressor.Close();
                    after_builtin = compressStream.ToArray().Length;
                }

            after_builtin.Should().BeGreaterThan(after);
        }
コード例 #38
0
 /// <summary>
 /// Deflate压缩函数
 /// </summary>
 /// <param name="strSource"></param>
 /// <returns></returns>
 public static string DeflateCompress(this string strSource)
 {
     if (strSource == null || strSource.Length > 8 * 1024)
     {
         throw new System.ArgumentException("字符串为空或长度太大!");
     }
     byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strSource);
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true))
         {
             stream.Write(buffer, 0, buffer.Length);
             stream.Close();
         }
         byte[] compressedData = ms.ToArray();
         ms.Close();
         return(Convert.ToBase64String(compressedData));      //将压缩后的byte[]转换为Base64String
     }
 }
コード例 #39
0
ファイル: Form1.cs プロジェクト: WangWeight/Protein
        //单纯为了字符串压缩:
        public string Compress(string strSource)
        {
            if (strSource == null || strSource.Length > 8 * 1024)
            {
                throw new System.ArgumentException("字符串为空或长度太大!");
            }

            System.Text.Encoding encoding = System.Text.Encoding.Unicode;
            byte[] buffer = encoding.GetBytes(strSource);
            //byte[] buffer = Convert.FromBase64String(strSource); //传入的字符串不一定是Base64String类型,这样写不行

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true);
            stream.Write(buffer, 0, buffer.Length);
            stream.Close();

            buffer = ms.ToArray();
            ms.Close();

            return(Convert.ToBase64String(buffer)); //将压缩后的byte[]转换为Base64String
        }
コード例 #40
0
ファイル: GZip.cs プロジェクト: dmhai/ColoPay
        /// <summary>
        /// Deflate压缩函数
        /// </summary>
        /// <remarks>针对JavaScript混合压缩算法</remarks>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public static string DeflateCompress(string strSource)
        {
            if (string.IsNullOrWhiteSpace(strSource)) return string.Empty;

            if (strSource.Length > 8 * 1024)
                throw new System.ArgumentException("YSWL.Common.DEncrypt.GZip.DeflateCompress 字符串长度超过上限");
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strSource);

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true))
                {
                    stream.Write(buffer, 0, buffer.Length);
                    stream.Close();
                }

                byte[] compressedData = ms.ToArray();
                ms.Close();

                return Convert.ToBase64String(compressedData);      //将压缩后的byte[]转换为Base64String
            }
        }
コード例 #41
0
ファイル: ZipEntry.cs プロジェクト: zy850580380/X
        internal void Write(IFormatterX writer)
        {
            Signature = ZipConstants.ZipEntrySignature;

            // 取得数据流位置
            RelativeOffsetOfLocalHeader = (UInt32)writer.Stream.Position;

            if (IsDirectory)
            {
                // 写入头部
                writer.Write(this);

                return;
            }

            Int32 dsLen = (Int32)DataSource.Length;

            //if (dsLen <= 0) CompressionMethod = CompressionMethod.Stored;

            // 计算签名和大小
            if (Crc == 0)
            {
                Crc = DataSource.GetCRC();
            }
            if (UncompressedSize == 0)
            {
                UncompressedSize = (UInt32)dsLen;
            }
            if (CompressionMethod == CompressionMethod.Stored)
            {
                CompressedSize = UncompressedSize;
            }
            if (DataSource.IsCompressed)
            {
                CompressedSize = (UInt32)dsLen;
            }

            // 写入头部
            writer.Write(this);

            // 没有数据,直接跳过
            if (dsLen <= 0)
            {
                return;
            }

            #region 写入文件数据
            // 数据源。只能用一次,因为GetData的时候把数据流移到了合适位置
            var source = DataSource.GetData();
            if (DataSource.IsCompressed)
            {
                // 可能数据源是曾经被压缩过了的,比如刚解压的实体
                source.CopyTo(writer.Stream, 0, dsLen);
                return;
            }

            switch (CompressionMethod)
            {
            case CompressionMethod.Stored:
                // 原始数据流直接拷贝到目标。必须指定大小,否则可能读过界
                source.CopyTo(writer.Stream, 0, dsLen);
                break;

            case CompressionMethod.Deflated:
            {
                // 记录数据流位置,待会用来计算已压缩大小
                Int64 p = writer.Stream.Position;
                using (var stream = new DeflateStream(writer.Stream, CompressionMode.Compress, true))
                {
                    source.CopyTo(stream);
                    stream.Close();
                }
                CompressedSize = (UInt32)(writer.Stream.Position - p);

                // 回头重新修正压缩后大小CompressedSize
                p = writer.Stream.Position;
                // 计算好压缩大小字段所在位置
                writer.Stream.Seek(RelativeOffsetOfLocalHeader + 18, SeekOrigin.Begin);
                //var wr = writer as IWriter2;
                //wr.Write(CompressedSize);
                writer.Write(CompressedSize);
                writer.Stream.Seek(p, SeekOrigin.Begin);
            }

            break;
            //case CompressionMethod.LZMA:
            //    {
            //        // 记录数据流位置,待会用来计算已压缩大小
            //        Int64 p = writer.Stream.Position;
            //        source.CompressLzma(writer.Stream, 10);
            //        CompressedSize = (UInt32)(writer.Stream.Position - p);

            //        // 回头重新修正压缩后大小CompressedSize
            //        p = writer.Stream.Position;
            //        // 计算好压缩大小字段所在位置
            //        writer.Stream.Seek(RelativeOffsetOfLocalHeader + 18, SeekOrigin.Begin);
            //        var wr = writer as IWriter2;
            //        wr.Write(CompressedSize);
            //        writer.Stream.Seek(p, SeekOrigin.Begin);
            //    }

            //    break;
            default:
                throw new XException("无法处理的压缩算法{0}!", CompressionMethod);
            }
            //#if DEBUG
            //            if (ts != null) ts.UseConsole = true;
            //#endif
            #endregion
        }
コード例 #42
0
    public static void Compress(string inputPath, string[] names, string outputPath, CompressMode mode)
    {
        var targets     = CreateTargets(names);
        var data        = ReadFile(inputPath);
        var offsets     = CreateOffsets(targets, data);
        var src_blocks  = CreateSrcBlocks(offsets, data);
        var copy_blocks = CreateCopyBlocks(src_blocks, data);

        if (File.Exists(outputPath))
        {
            File.Delete(outputPath);
        }
        using (var outputFile = new FileStream(outputPath, FileMode.CreateNew, FileAccess.Write)) {
            // header
            uint magic;
            switch (mode)
            {
            case CompressMode.Raw:
                magic = MAGIC_RAW;
                break;

            case CompressMode.Deflate:
                magic = MAGIC_DEFLATE;
                break;

            case CompressMode.LZMA:
                magic = MAGIC_LZMA;
                break;

            default:
                throw new Exception("Unknown compress mode");
            }

            outputFile.Write(uint2bytes(magic), 0, 4);
            outputFile.Write(int2bytes(data.Length), 0, 4);

            // blocks
            switch (mode)
            {
            case CompressMode.Raw:
                WriteBlocksToStream(copy_blocks, outputFile, data);
                break;

            case CompressMode.Deflate:
                using (var zipstream = new System.IO.Compression.DeflateStream(outputFile, System.IO.Compression.CompressionMode.Compress, true)) {
                    WriteBlocksToStream(copy_blocks, zipstream, data);
                    zipstream.Close();
                }
                break;

            case CompressMode.LZMA:
                using (var memstream = new MemoryStream()) {
                    WriteBlocksToStream(copy_blocks, memstream, data);
                    memstream.Flush();
                    var buf = memstream.ToArray();
                    using (var m = new MemoryStream(buf)) {
                        SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();
                        Int32 dictSize32 = (Int32)LZMA_DICT_SIZE;
                        coder.SetCoderProperties(new SevenZip.CoderPropID[] { SevenZip.CoderPropID.DictionarySize }, new object[] { dictSize32 });
                        coder.WriteCoderProperties(outputFile);
                        outputFile.Write(int2bytes(buf.Length), 0, 4);
                        coder.Code(m, outputFile, buf.Length, -1, null);
                    }
                }
                break;
            }

            var output_length = outputFile.Length;
            outputFile.Flush();
            outputFile.Close();

            Debug.LogFormat("Reducled to {0:F2}% | {1}:{2} => {3}:{4}",
                            100.0f * output_length / data.Length,
                            inputPath, data.Length,
                            outputPath, output_length);
        }
    }