Write() публичный Метод

public Write ( byte array, int offset, int count ) : void
array byte
offset int
count int
Результат void
Пример #1
0
        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);
        }
Пример #2
0
        public static byte[] Compress(byte[] buffer)
        {
            byte[] comp;
            using (var output = new MemoryStream()) {
                using (var deflate = new DeflateStream(output, CompressionMode.Compress))
                    deflate.Write(buffer, 0, buffer.Length);
                comp = output.ToArray();
            }

            // Refer to http://www.ietf.org/rfc/rfc1950.txt for zlib format
            const byte CM = 8;
            const byte CINFO = 7;
            const byte CMF = CM | (CINFO << 4);
            const byte FLG = 0xDA;

            byte[] result = new byte[comp.Length + 6];
            result[0] = CMF;
            result[1] = FLG;
            Buffer.BlockCopy(comp, 0, result, 2, comp.Length);

            uint cksum = ADLER32(buffer);
            var index = result.Length - 4;
            result[index++] = (byte)(cksum >> 24);
            result[index++] = (byte)(cksum >> 16);
            result[index++] = (byte)(cksum >> 8);
            result[index++] = (byte)(cksum >> 0);

            return result;
        }
Пример #3
0
 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;
 }
Пример #4
0
		/// <summary>
		/// ѹËõ¶þ½øÖÆÁ÷
		/// </summary>
		/// <param name="stream">´ýѹËõµÄ¶þ½øÖÆÁ÷</param>
		/// <returns>·µ»ØѹËõºóµÄ¶þ½øÖÆÁ÷</returns>
		/// <remarks>
		/// ѹËõ¶þ½øÖÆÁ÷£ºÍ¨¹ýCreateTempFile()Éú³ÉÁÙʱÎļþ£»Éú³É´ýѹËõµÄ¶þ½øÖÆÁ÷inStream£»·µ»ØѹËõºóµÄ¶þ½øÖÆÁ÷outStream£»
		/// <code source="..\Framework\TestProjects\DeluxeWorks.Library.Test\Compression\GenericZipTest.cs" region="StreamZipTest" lang="cs" title="ѹËõ¶þ½øÖÆÁ÷" />
		/// </remarks>
		public static Stream ZipStream(Stream stream)
		{
			if (false == PreCheck(stream))
				return null;

			#region compress stream by buffers

			MemoryStream result = new MemoryStream();

			Byte[] buff = new Byte[BufferSize];

			using (DeflateStream compressStream = new DeflateStream(result, CompressionMode.Compress, true))
			{
				int cnt = stream.Read(buff, 0, BufferSize);
				while (cnt > 0)
				{
					compressStream.Write(buff, 0, cnt);
					cnt = stream.Read(buff, 0, BufferSize);
				}
			}

			#endregion

			return result;
		}
Пример #5
0
		public void Compress(ref byte[] buffer, ref int length)
		{
			using (var outS = new MemoryStream())
			{
				using (var ds = new DeflateStream(outS, CompressionMode.Compress, true))
				{
					ds.Write(buffer, 0, length);
				}

				outS.Position = 0;

				// Recycle the buffer?
				if (outS.Length <= buffer.Length)
				{
					length = outS.Read(buffer, 0, buffer.Length);

					// Heartbleed: Nope; zero-fill the remaining buffer!
					for (var i = length; i < buffer.Length; i++)
					{
						buffer[i] = 0;
					}
				}
				else
				{
					buffer = outS.ToArray();
					length = buffer.Length;
				}
			}
		}
Пример #6
0
        /// <summary>
        /// 지정된 데이타를 압축한다.
        /// </summary>
        /// <param name="input">압축할 Data</param>
        /// <returns>압축된 Data</returns>
        public override byte[] Compress(byte[] input) {
            if(IsDebugEnabled)
                log.Debug(CompressorTool.SR.CompressStartMsg);

            // check input data
            if(input.IsZeroLength()) {
                if(IsDebugEnabled)
                    log.Debug(CompressorTool.SR.InvalidInputDataMsg);

                return CompressorTool.EmptyBytes;
            }

            byte[] output;
            using(var outStream = new MemoryStream()) {
                using(var deflate = new DeflateStream(outStream, CompressionMode.Compress)) {
                    deflate.Write(input, 0, input.Length);
                }
                output = outStream.ToArray();
            }

            if(IsDebugEnabled)
                log.Debug(CompressorTool.SR.CompressResultMsg, input.Length, output.Length, output.Length / (double)input.Length);

            return output;
        }
Пример #7
0
 private string GetEncodedReportFile()
 {
     string report = null;
      try {
     string exePath = Application.ExecutablePath;
     string appPath = Path.GetDirectoryName(exePath);
     string logFileName = Path.Combine(appPath, defaultLogFileName);
     if (!File.Exists(logFileName)) {
        return null;
     }
     byte[] logFileBytes = File.ReadAllBytes(logFileName);
     using (MemoryStream ms = new MemoryStream()) {
        using (DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, false)) {
           deflateStream.Write(logFileBytes, 0, logFileBytes.Length);
           byte[] compressedBytes = ms.ToArray();
           report = Convert.ToBase64String(compressedBytes);
        }
     }
      }
      catch (ArgumentException e) {
     Trace.TraceWarning(e.ToString());
      }
      catch (IOException e) {
     Trace.TraceWarning(e.ToString());
      }
      catch (SecurityException e) {
     Trace.TraceWarning(e.ToString());
      }
      catch (UnauthorizedAccessException e) {
     Trace.TraceWarning(e.ToString());
      }
      return report;
 }
Пример #8
0
		/// <summary>
		/// Returns compressed version of given string.
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static string Compress(string str)
		{
			var barr = Encoding.Unicode.GetBytes(str + '\0'); // Why did we append a null byte... was this required?
			using (var mout = new MemoryStream())
			{
				// Deflate should use optimal compression level by default (0, as defined by .NET 4.5).
				using (var df = new DeflateStream(mout, CompressionMode.Compress))
				{
					// Write compressed data to memory stream.
					df.Write(barr, 0, barr.Length);
				}

				// Compression method
				int cmf = 8; // cm
				cmf += 7 << 4; // cinfo

				// Flags
				int flg = 2 << 6; // Compression level
				int n = ((cmf * 256) + flg) % 31;
				if (n != 0)
					flg += 31 - n; // Check bits

				// <length>;<cmf><flg><data><checksum>
				return string.Format("{0};{1:x02}{2:x02}{3}{4:x08}", barr.Length, cmf, flg, BitConverter.ToString(mout.ToArray()).Replace("-", "").ToLower(), ComputeAdler32(barr));
			}
		}
Пример #9
0
            public byte[] Compress( byte[] buffer )
            {
                MemoryStream result = new MemoryStream();
                int offset = 0;

                BinaryWriter bw = new BinaryWriter( result );

                bw.Write( new byte[] { 0x54, 0x4C, 0x5A, 0x43 } );
                bw.Write( (byte)0x01 );
                bw.Write( (byte)0x02 );
                bw.Write( (byte)0x00 );
                bw.Write( (byte)0x00 );
                bw.Write( (int)0 );   // compressed size - we'll fill this in once we know it
                bw.Write( (int)buffer.Length );   // decompressed size
                bw.Write( (int)0 );   // unknown, 0
                bw.Write( (int)0 );   // unknown, 0

                using ( DeflateStream compressionStream = new DeflateStream( result, CompressionLevel.Optimal ) ) {
                    compressionStream.Write( buffer );
                }

                byte[] retval = result.ToArray();

                // fill in compressed size
                Util.CopyByteArrayPart( BitConverter.GetBytes( (int)retval.Length ), 0, retval, 8, 4 );

                return retval;
            }
Пример #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
 public void Compress(string content, Stream targetStream)
 {
     using (var writer = new DeflateStream(targetStream, CompressionMode.Compress))
     {
         var bytes = Encoding.UTF8.GetBytes(content);
         writer.Write(bytes, 0, bytes.Length);
     }
 }
Пример #12
0
 internal static byte[] Compress(ReadOnlySpan <byte> data)
 {
     using var val = new MemoryStream(CompressedLengthEstimate(data));
     using (var compressor = new IOC.DeflateStream(val, IOC.CompressionLevel.Optimal)) {
         compressor.Write(data);
     }
     return(val.GetArray());
 }
Пример #13
0
 /// <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
 public static byte[] Compress(byte[] raw, int offset, int count)
 {
     var memory = new MemoryStream();
     using (var deflate = new DeflateStream(memory, CompressionMode.Compress, true))
     {
         deflate.Write(raw, offset, count);
         return memory.ToArray();
     }
 }
Пример #15
0
        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();
        }
Пример #16
0
 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();
 }
Пример #17
0
 /// <summary>
 /// 转换指定字节数组的指定区域。
 /// </summary>
 /// <param name="inputBuffer">要为其计算转换的输入。</param>
 /// <param name="inputOffset">字节数组中的偏移量,从该位置开始使用数据。</param>
 /// <param name="inputCount">字节数组中用作数据的字节数。</param>
 /// <param name="outputBuffer">将转换写入的输出。</param>
 /// <param name="outputOffset">输出字节数组中的偏移量,从该位置开始写入数据。</param>
 /// <returns>计算所得的转换的字节数。</returns>
 public override int CompressBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
 {
     using (var ms = new MemoryStream(outputBuffer, outputOffset, outputBuffer.Length - outputOffset, true)) {
         using (var outStream = new DeflateStream(ms, CompressionMode.Compress)) {
             outStream.Write(inputBuffer, inputOffset, inputCount);
             outStream.Flush();
         }
         return (int)ms.Position;
     }
 }
Пример #18
0
 /// <summary>
 /// 转换指定字节数组的指定区域。
 /// </summary>
 /// <param name="inputBuffer">要为其计算转换的输入。</param>
 /// <param name="inputOffset">字节数组中的偏移量,从该位置开始使用数据。</param>
 /// <param name="inputCount">字节数组中用作数据的字节数。</param>
 /// <returns>计算所得的转换。</returns>
 public override byte[] CompressFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
 {
     using (var ms = new MemoryStream()) {
         using (var outStream = new DeflateStream(ms, CompressionMode.Compress)) {
             outStream.Write(inputBuffer, inputOffset, inputCount);
             outStream.Flush();
         }
         return ms.ToArray();
     }
 }
Пример #19
0
 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;
 }
Пример #20
0
 /// <summary>
 /// Decompress
 /// </summary>
 /// <param name="values"></param>
 /// <returns></returns>
 public static byte[] Decompress(byte[] values)
 {
     // chop off header and tail
     byte[] raw = new byte[values.Length - 6];
     Array.Copy(values, 2, raw, 0, values.Length - 6);
     MemoryStream msOut = new MemoryStream(values.Length);
     DeflateStream deflator = new DeflateStream(msOut, CompressionMode.Decompress);
     deflator.Write(raw, 0, values.Length);
     return msOut.ToArray();
 }
Пример #21
0
 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();
     }
 }
Пример #22
0
		public static byte[] Compress( byte[] input, bool addFirst2Bytes ) {
			MemoryStream output = new MemoryStream();
			output.Write( new byte[] { 120, 156 }, 0, 2 );

			using( DeflateStream Deflate = new DeflateStream( output, CompressionMode.Compress ) ) {
				Deflate.Write( input, 0, input.Length );
			}

			return output.ToArray();
		}
 public byte[] Compress(byte[] bytes)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress, leaveOpen: true))
         {
             deflateStream.Write(bytes, 0, bytes.Length);
         }
         return memoryStream.ToArray();
     }
 }
Пример #24
0
    static public byte[] Deflate(byte[] input)
    {
        using var deflatedStream = new System.IO.MemoryStream();

        using var compressor = new System.IO.Compression.DeflateStream(
                  deflatedStream, System.IO.Compression.CompressionMode.Compress);

        compressor.Write(input, 0, input.Length);
        compressor.Close();
        return(deflatedStream.ToArray());
    }
Пример #25
0
 private static byte[] DeflateCompressor(byte[] input, int length)
 {
     using (var stream = new MemoryStream())
     {
         using (var deflate = new DeflateStream(stream, CompressionMode.Compress))
         {
             deflate.Write(input, 0, length);
         }
         return stream.ToArray();
     }
 }
Пример #26
0
        public static Stream DeflateCompressStream(string textToCompress) {
            var data = Encoding.UTF8.GetBytes(textToCompress);

            using (var ms = new MemoryStream()) {
                using (var zip = new DeflateStream(ms, CompressionMode.Compress)) {
                    zip.Write(data, 0, data.Length);
                }

                return new MemoryStream(ms.ToArray());
            }
        }
Пример #27
0
        /// <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;
        }
Пример #28
0
 private static byte[] deflateEncode(byte[] input)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         using (DeflateStream dfs = new DeflateStream(ms, CompressionMode.Compress, true))
         {
             dfs.Write(input, 0, input.Length);
         }
         return ms.ToArray();
     }
 }
 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();
     }
 }
Пример #30
0
 public static byte[] Compress(byte[] data, int startPos)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         using (DeflateStream ds = new DeflateStream(ms, CompressionLevel.Fastest))
         {
             ds.Write(data, startPos, data.Length - startPos);
         }
         return ms.ToArray();
     }
 }
Пример #31
0
        public byte[] Compress(byte[] plainText)
        {
            using (MemoryStream output = new MemoryStream())
            {
                using (DeflateStream gzip =new DeflateStream(output, CompressionMode.Compress))
                {
                    gzip.Write(plainText,0,plainText.Length);
                }

                return output.ToArray();
            }
        }
Пример #32
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();
            }
        }
Пример #33
0
        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
 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);
 }
Пример #35
0
 internal static byte[] CompressTest(byte[] data)
 {
     IOC.DeflateStream?compressor = null;
     try {
         using var val = new MemoryStream(CompressedLengthEstimate(data));
         using (compressor = new IOC.DeflateStream(val, IOC.CompressionLevel.Optimal)) {
             compressor.Write(data, 0, data.Length);
         }
         return(val.GetArray());
     }
     catch (DllNotFoundException) when(compressor is not null)
     {
         GC.SuppressFinalize(compressor);
         throw;
     }
 }
Пример #36
0
        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);
        }
        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);
        }
Пример #38
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);
        }
Пример #39
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
     }
 }
Пример #40
0
        //单纯为了字符串压缩:
        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
        }
Пример #41
0
        /// <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
            }
        }
Пример #42
0
        /// <summary>
        /// Decompresses deflate data to original data.
        /// </summary>
        /// <param name="strValue">A string that you want to be compressed.</param>
        /// <returns>Compressed string in base64 encoding</returns>
        public static string DeflateCompress(this string strValue)
        {
            if (String.IsNullOrEmpty(strValue))
            {
                throw new ArgumentNullException("strValue");
            }

            byte[] RawData = System.Text.Encoding.UTF8.GetBytes(strValue); // RawData variable memory leak.

            using (MemoryStream ms = new MemoryStream())
            {
                return(ms.TryCatchThrow(p =>
                {
                    using (DeflateStream ds = new DeflateStream(p, CompressionMode.Compress))
                    {
                        ds.Write(RawData, 0, RawData.Length);
                    }

                    return Convert.ToBase64String(p.ToArray());
                }));
            }
        }
Пример #43
0
    internal static unsafe T[] Compress <T>(ReadOnlySpan <byte> data) where T : unmanaged
    {
        if (typeof(T) == typeof(byte))
        {
            return((T[])(object)CompressBytes(data));
        }

        long requiredSize = CompressedLengthMax(data);
        long capacity     = AlignCount <T>(requiredSize);

        if (capacity > int.MaxValue)
        {
            var resultArray  = CompressBytes(data);
            T[] copiedResult = GC.AllocateUninitializedArray <T>(AlignCount <T>(resultArray.Length));
            resultArray.AsReadOnlySpan().CopyTo(copiedResult.AsSpan().AsBytes());
            return(copiedResult);
        }

        T[]  result = GC.AllocateUninitializedArray <T>((int)capacity);
        long resultLength;

        fixed(T *resultPtr = result)
        {
            using var resultStream = new UnmanagedMemoryStream((byte *)resultPtr, result.Length * sizeof(T));

            using var compressor = new IOC.DeflateStream(resultStream, IOC.CompressionLevel.Optimal);
            compressor.Write(data.ToArray(), 0, data.Length);
            compressor.Flush();
            resultLength = resultStream.Position;
        }

        if (result.Length != resultLength)
        {
            Array.Resize(ref result, (int)resultLength);
        }

        return(result);
    }
Пример #44
0
        /// <summary>
        /// Compresses data using Deflate format
        /// </summary>
        /// <param name="RawData">A byte array that you want to be compressed.</param>
        /// <returns>Compressed bytes</returns>
        public static byte[] DeflateCompress(this byte[] RawData)
        {
            if (RawData == null)
            {
                throw new ArgumentException("RawData");
            }
            if (RawData.Length < 1)
            {
                throw new ArgumentOutOfRangeException("RawData", "Empty byte array.");
            }

            using (MemoryStream ms = new MemoryStream())
            {
                return(ms.TryCatchThrow(p =>
                {
                    using (DeflateStream ds = new DeflateStream(p, CompressionMode.Compress))
                    {
                        ds.Write(RawData, 0, RawData.Length);
                    }

                    return p.ToArray();
                }));
            }
        }
        public void CompressorNotClosed_DecompressorStillSuccessful(bool closeCompressorBeforeDecompression)
        {
            const string Input = "example";

            var ms = new MemoryStream();

            using (var compressor = new DeflateStream(ms, CompressionLevel.Optimal, leaveOpen: closeCompressorBeforeDecompression))
            {
                compressor.Write(Encoding.ASCII.GetBytes(Input));
                compressor.Flush();
                if (closeCompressorBeforeDecompression)
                {
                    compressor.Dispose();
                }

                ms.Position = 0;
                using (var decompressor = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
                {
                    var decompressed = new MemoryStream();
                    decompressor.CopyTo(decompressed);
                    Assert.Equal(Input, Encoding.ASCII.GetString(decompressed.ToArray()));
                }
            }
        }
Пример #46
0
        /// <summary>
        /// Compresses a byte array using a specified algorithm.
        /// </summary>
        /// <param name="dataToCompress">The byte array to compress.</param>
        /// <param name="startIndex">The zero-based position in the array where the compression begins.</param>
        /// <param name="algorithm">The algorithm used to compress the array.
        /// This method will check the compression rate after the compression is done,
        /// and if it is not smaller than 1 (indicating the "compressed" data takes even more space than the original data and the compression is ineffective),
        /// the original data will be returned and this argument will be set <c>ByteCompressionMethods.None</c>.</param>
        /// <returns>
        /// The compressed byte array if the compression is successful;
        /// or the bytes in the original byte array from <paramref name="startIndex"/> to the end if the compression is ineffective.
        /// </returns>
        public static byte[] Compress(this byte[] dataToCompress, int startIndex, ref ByteCompressionMethods algorithm)
        {
            byte[] compressedData;
            using (MemoryStream compressedMs = new MemoryStream())
            {
                switch (algorithm)
                {
                case ByteCompressionMethods.GZipOptimal:
                {
                    using (GZipStream gzs = new GZipStream(compressedMs, CompressionLevel.Optimal))
                        gzs.Write(dataToCompress, startIndex, dataToCompress.Length - startIndex);

                    compressedData = compressedMs.ToArray();

                    break;
                }

                case ByteCompressionMethods.GZipFast:
                {
                    using (GZipStream gzs = new GZipStream(compressedMs, CompressionLevel.Fastest))
                        gzs.Write(dataToCompress, startIndex, dataToCompress.Length - startIndex);

                    compressedData = compressedMs.ToArray();

                    break;
                }

                case ByteCompressionMethods.DeflateOptimal:
                {
                    using (DeflateStream ds = new DeflateStream(compressedMs, CompressionLevel.Optimal))
                        ds.Write(dataToCompress, startIndex, dataToCompress.Length - startIndex);
                    compressedData = compressedMs.ToArray();

                    break;
                }

                case ByteCompressionMethods.DeflateFast:
                {
                    using (DeflateStream ds = new DeflateStream(compressedMs, CompressionLevel.Fastest))
                        ds.Write(dataToCompress, startIndex, dataToCompress.Length - startIndex);
                    compressedData = compressedMs.ToArray();

                    break;
                }

                default:
                {
                    var tmpMs = new MemoryStream(dataToCompress, startIndex, dataToCompress.Length - startIndex);
                    return(tmpMs.ToArray());
                }
                }
            }

            if (compressedData.Length < dataToCompress.Length)
            {
                return(compressedData);
            }
            else
            {
                algorithm = ByteCompressionMethods.None;
                return(dataToCompress);
            }
        }
Пример #47
0
 public override void Write(byte[] array, int offset, int count)
 {
     CheckDeflateStream();
     _deflateStream.Write(array, offset, count);
 }
Пример #48
0
 public override void Write(byte[] src, int src_offset, int count)
 {
     deflateStream.Write(src, src_offset, count);
 }
Пример #49
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     CheckDeflateStream();
     _deflateStream.Write(buffer, offset, count);
 }