This filter stream is used to compress a stream into a "GZIP" stream. The "GZIP" format is described in RFC 1952. author of the original java version : John Leuner
상속: ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream
예제 #1
0
        public void BigStream()
        {
            window_ = new WindowedStream(0x3ffff);
            outStream_ = new GZipOutputStream(window_);
            inStream_ = new GZipInputStream(window_);

            long target = 0x10000000;
            readTarget_ = writeTarget_ = target;

            Thread reader = new Thread(Reader);
            reader.Name = "Reader";
            reader.Start();

            Thread writer = new Thread(Writer);
            writer.Name = "Writer";

            DateTime startTime = DateTime.Now;
            writer.Start();

            writer.Join();
            reader.Join();

            DateTime endTime = DateTime.Now;

            TimeSpan span = endTime - startTime;
            Console.WriteLine("Time {0}  processes {1} KB/Sec", span, (target / 1024) / span.TotalSeconds);
        }
예제 #2
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 compressedStream = new MemoryStream(input.Length)) {
                using(var gzs = new GZipOutputStream(compressedStream)) {
                    gzs.SetLevel(ZipLevel);
                    gzs.Write(input, 0, input.Length);
                    gzs.Finish();
                }
                output = compressedStream.ToArray();
            }

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

            return output;
        }
예제 #3
0
        public void TestGZip()
        {
            MemoryStream ms = new MemoryStream();
            GZipOutputStream outStream = new GZipOutputStream(ms);

            byte[] buf = new byte[100000];
            System.Random rnd = new Random();
            rnd.NextBytes(buf);

            outStream.Write(buf, 0, buf.Length);
            outStream.Flush();
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            GZipInputStream inStream = new GZipInputStream(ms);
            byte[] buf2 = new byte[buf.Length];
            int    pos  = 0;
            while (true) {
                int numRead = inStream.Read(buf2, pos, 4096);
                if (numRead <= 0) {
                    break;
                }
                pos += numRead;
            }

            for (int i = 0; i < buf.Length; ++i) {
                Assertion.AssertEquals(buf2[i], buf[i]);
            }
        }
예제 #4
0
파일: RequestParse.cs 프로젝트: 0jpq0/Scut
        public static byte[] CtorErrMsg(string msg, NameValueCollection requestParam)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                //包总长度
                int len = 0;
                long pos = 0;
                //包总长度,占位
                WriteValue(ms, len);
                int actionid = Convert.ToInt32(requestParam["actionid"]);
                //StatusCode
                WriteValue(ms, 10001);
                //msgid
                WriteValue(ms, Convert.ToInt32(requestParam["msgid"]));
                WriteValue(ms, msg);
                WriteValue(ms, actionid);
                WriteValue(ms, "st");
                //playerdata
                WriteValue(ms, 0);
                //固定0
                WriteValue(ms, 0);
                ms.Seek(pos, SeekOrigin.Begin);
                WriteValue(ms, (int)ms.Length);

                using (var gms = new MemoryStream())
                using (var gzs = new GZipOutputStream(gms))
                {
                    gzs.Write(ms.GetBuffer(), 0, (int)ms.Length);
                    gzs.Flush();
                    gzs.Close();
                    return gms.ToArray();
                }
            }
        }
예제 #5
0
		/// <summary>
		/// Creates a GZipped Tar file from a source directory
		/// </summary>
		/// <param name="outputTarFilename">Output .tar.gz file</param>
		/// <param name="sourceDirectory">Input directory containing files to be added to GZipped tar archive</param>
		public static void CreateTar(string outputTarFilename, string sourceDirectory)
		{
			using (FileStream fs = new FileStream(outputTarFilename, FileMode.Create, FileAccess.Write, FileShare.None))
			using (Stream gzipStream = new GZipOutputStream(fs))
			using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzipStream))
				AddDirectoryFilesToTar(tarArchive, sourceDirectory, true);
		}
        public void GZip_Compress_Extract_Test() {
            var plainStream = PlainText.ToStream();
            plainStream.Seek(0, SeekOrigin.Begin);

            var plainData = Encoding.UTF8.GetBytes(PlainText);
            byte[] compressedData;
            byte[] extractedData;

            // Compress
            using(var compressedStream = new MemoryStream())
            using(var gzs = new GZipOutputStream(compressedStream)) {
                gzs.SetLevel(5);
                gzs.Write(plainData, 0, plainData.Length);
                gzs.Finish();
                compressedData = compressedStream.ToArray();
            }

            Assert.IsNotNull(compressedData);

            // Extract
            using(var compressedStream = new MemoryStream(compressedData)) {
                // compressedStream.Seek(0, SeekOrigin.Begin);
                using(var gzs = new GZipInputStream(compressedStream))
                using(var extractedStream = new MemoryStream()) {
                    StreamTool.CopyStreamToStream(gzs, extractedStream);
                    extractedData = extractedStream.ToArray();
                }
            }

            Assert.IsNotNull(extractedData);
            string extractedText = Encoding.UTF8.GetString(extractedData).TrimEnd('\0');

            Assert.AreEqual(PlainText, extractedText);
        }
예제 #7
0
 /// <summary>
 /// 压缩文件为gz文件
 /// </summary>
 /// <param name="sourcefilename">压缩的文件路径</param>
 /// <param name="zipfilename">压缩后的gz文件路径</param>
 /// <returns></returns>
 public static bool Compress(string sourcefilename, string zipfilename)
 {
     bool blResult;//表示压缩是否成功的返回结果
     //为源文件创建读取文件的流实例
     FileStream srcFile = File.OpenRead(sourcefilename);
     //为压缩文件创建写入文件的流实例
     GZipOutputStream zipFile = new GZipOutputStream(File.Open(zipfilename, FileMode.Create));
     try
     {
         byte[] FileData = new byte[srcFile.Length];//创建缓冲数据
         srcFile.Read(FileData, 0, (int)srcFile.Length);//读取源文件
         zipFile.Write(FileData, 0, FileData.Length);//写入压缩文件
         blResult = true;
         return blResult;
     }
     catch
     {
         blResult = false;
         return blResult;
     }
     finally
     {
         srcFile.Close();//关闭源文件
         zipFile.Close();//关闭压缩文件
     }
 }
예제 #8
0
		public void TestGZip()
		{
			MemoryStream ms = new MemoryStream();
			GZipOutputStream outStream = new GZipOutputStream(ms);

			byte[] buf = new byte[100000];
			System.Random rnd = new Random();
			rnd.NextBytes(buf);

			outStream.Write(buf, 0, buf.Length);
			outStream.Flush();
			outStream.Finish();

			ms.Seek(0, SeekOrigin.Begin);

			GZipInputStream inStream = new GZipInputStream(ms);
			byte[] buf2 = new byte[buf.Length];
			int currentIndex = 0;
			int count = buf2.Length;
			
			while (true) {
				int numRead = inStream.Read(buf2, currentIndex, count);
				if (numRead <= 0) {
					break;
				}
				currentIndex += numRead;
				count -= numRead;
			}

			Assert.AreEqual(0, count);
			
			for (int i = 0; i < buf.Length; ++i) {
				Assert.AreEqual(buf2[i], buf[i]);
			}
		}
		public void GetDataSet()
		{
			SoapContext sc = HttpSoapContext.ResponseContext;
			if (null == sc)
			{
				throw new ApplicationException("Only SOAP requests allowed");
			}

			SqlConnection conn = new SqlConnection(@"data source=(local)\NetSDK;" +
				"initial catalog=Northwind;integrated security=SSPI");

			SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM customers", conn);
			DataSet ds = new DataSet("CustomerDS");
			da.Fill(ds, "Customers");
			
			// dispose of all objects that are no longer necessary
			da.Dispose();
			conn.Dispose();

			MemoryStream memoryStream = new MemoryStream(1024);
			GZipOutputStream gzipStream = new GZipOutputStream(memoryStream);
			ds.WriteXml(gzipStream);
			gzipStream.Finish();
			memoryStream.Seek(0, SeekOrigin.Begin);

			DimeAttachment dimeAttachment = new DimeAttachment("application/x-gzip",
				TypeFormatEnum.MediaType, 
				memoryStream);

			sc.Attachments.Add(dimeAttachment);
		}
예제 #10
0
        public string CreateTarGzFile(List<string> files, string destinationFolder)
        {
            var fileName = Path.Combine(destinationFolder, DateTime.Now.Ticks.ToString() + ".tar.gz");
            Stream outStream = File.Create(fileName);
            Stream gzoStream = new GZipOutputStream(outStream);
            TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);

            // Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
            // and must not end with a slash, otherwise cuts off first char of filename
            // This is scheduled for fix in next release
            tarArchive.RootPath = destinationFolder.Replace('\\', '/');
            tarArchive.RootPath.TrimEnd("/".ToCharArray());

            TarEntry tarEntry = TarEntry.CreateEntryFromFile(destinationFolder);
            tarArchive.WriteEntry(tarEntry, false);

            foreach (string filename in files)
            {
                tarEntry = TarEntry.CreateEntryFromFile(filename);
                tarArchive.WriteEntry(tarEntry, true);
            }

            tarArchive.Close();

            return fileName;
        }
예제 #11
0
 /// <summary>
 /// Write content to the stream and have it compressed using gzip.
 /// </summary>
 /// <param name="buffer">The bytes to write</param>
 /// <param name="offset">The offset into the buffer to start reading bytes</param>
 /// <param name="count">The number of bytes to write</param>
 public override void Write(byte[] buffer, int offset, int count) {
   //      GZipOutputStream stream = new GZipOutputStream(BaseStream);
   //      stream.Write(buffer, offset, count);
   //      stream.Finish();
   if (m_stream == null)
     m_stream = new GZipOutputStream(BaseStream);
   m_stream.Write(buffer, offset, count);
 }
예제 #12
0
 /// <summary>
 /// Compresses byte array using gzip
 /// Compressed data is returned as a byte array
 /// </summary>
 /// <param name="inBytes">The bytes to compress</param>
 public static byte[] compress_gzip(byte[] inBytes)
 {
     MemoryStream ContentsGzippedStream = new MemoryStream();	//create the memory stream to hold the compressed file
     Stream s = new GZipOutputStream(ContentsGzippedStream);		//create the gzip filter
     s.Write(inBytes, 0, inBytes.Length);				        //write the file contents to the filter
     s.Flush();													//make sure everythings ready
     s.Close();													//close and write the compressed data to the memory stream
     return ContentsGzippedStream.ToArray();
 }
예제 #13
0
 public static void GZip(FileInfo fi)
 {
     byte[] dataBuffer = new byte[4096];
     using (Stream s = new GZipOutputStream(File.Create(fi.FullName + ".gz")))
     using (FileStream fs = fi.OpenRead())
     {
         StreamUtils.Copy(fs, s, dataBuffer);
     }
 }
예제 #14
0
 public static string Compress(string sourceFile){
     byte[] dataBuffer = new byte[4096];
     string destFile = sourceFile + ".gz";
     using (Stream gs = new GZipOutputStream(File.Create(destFile))) {
         using (FileStream fs = File.OpenRead(sourceFile)) {
             StreamUtils.Copy(fs, gs, dataBuffer);
         }
     }
     return destFile;
 }
예제 #15
0
        /// <summary>
        /// 压缩字节数组
        /// </summary>
        /// <param name="str"></param>
        public static byte[] ByteCompress(byte[] inputBytes)
        {
            MemoryStream     ms   = new MemoryStream();
            GZipOutputStream gzip = new GZipOutputStream(ms);

            gzip.Write(inputBytes, 0, inputBytes.Length);
            gzip.Close();
            byte[] press = ms.ToArray();
            return(press);
        }
예제 #16
0
 /// <summary>
 /// 压缩byte数组
 /// </summary>
 /// <param name="inBytes">需要压缩的byte数组</param>
 /// <returns>压缩好的byte数组</returns>
 public static byte[] CompressByte(byte[] inBytes)
 {
     MemoryStream outStream = new MemoryStream();
     Stream zipStream = new GZipOutputStream(outStream);
     zipStream.Write(inBytes, 0, inBytes.Length);
     zipStream.Close();
     byte[] outData = outStream.ToArray();
     outStream.Close();
     return outData;
 }
예제 #17
0
 /// <summary>
 /// 压缩字节数组
 /// 返回:已压缩的字节数组
 /// </summary>
 /// <param name="bytData">待压缩的字节数组</param>
 /// <returns></returns>
 public static byte[] CompressBytes(byte[] data)
 {
     MemoryStream o = new MemoryStream();
     Stream s = new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(o);
     s.Write(data, 0, data.Length);
     s.Close();
     o.Flush();
     o.Close();
     return o.ToArray();
 }
예제 #18
0
 public static byte[] Serialize(object obj)
 {
     MemoryStream ms = new MemoryStream();
     using (GZipOutputStream stm = new GZipOutputStream(ms))
     {
         BinaryFormatter bf = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Persistence));
         bf.Serialize(stm, obj);
     }
     return ms.GetBuffer();
 }
예제 #19
0
        public static byte[] returnZippedbyteArray(string stringToZip)
        {
            MemoryStream memStream = new MemoryStream();
            Stream compressedStream = new GZipOutputStream(memStream);
            byte[] byteArrayToZip = Encoding.UTF8.GetBytes(stringToZip.ToCharArray());

            compressedStream.Write(byteArrayToZip ,0,byteArrayToZip.Length);
            compressedStream.Flush();
            compressedStream.Close();
            return memStream.ToArray();
        }
예제 #20
0
파일: ZipFile.cs 프로젝트: zhangf911/GDGeek
        public static byte[] Compression(byte[] data)
        {
            MemoryStream o = new MemoryStream();
            Stream       s = new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(o);

            s.Write(data, 0, data.Length);
            s.Close();
            o.Flush();
            o.Close();
            return(o.ToArray());
        }
예제 #21
0
 public static void SaveFile(string fileName, byte[] data)
 {
     if (File.Exists(fileName)) File.Delete(fileName);
     using (FileStream targetStream = File.OpenWrite(fileName))
     {
         using (GZipOutputStream targetStreamGzip = new GZipOutputStream(targetStream))
         {
             MemoryStream saveTemp = new MemoryStream(data);
             CopyStream(saveTemp, targetStreamGzip);
         }
     }
 }
예제 #22
0
파일: ByteEx.cs 프로젝트: Venbb/mgame
		/// <summary>
		/// 压缩字节数组
		/// </summary>
		/// <param name="inputBytes">Input bytes.</param>
		public static byte[] Compress (byte[] inputBytes)
		{
			using (var outStream = new MemoryStream ())
			{
				using (var zipStream = new GZipOutputStream (outStream))
				{
					zipStream.Write (inputBytes, 0, inputBytes.Length);
					zipStream.Close ();	
				}
				return outStream.ToArray ();
			}	
		}
예제 #23
0
    public byte[] zip(string input)
    {
        byte[] data = Encoding.UTF8.GetBytes (input);

        using (MemoryStream memory = new MemoryStream()) {
            using (GZipOutputStream gzip = new GZipOutputStream(memory)) {
                gzip.Write (data, 0, data.Length);
            }//using

            return memory.ToArray ();
        }//using
    }
예제 #24
0
        static private void CreateTarGZ(string tgzFilename, string sourceDirectory)
        {
            Stream outStream = File.Create(tgzFilename);
            Stream gzoStream = new GZipOutputStream(outStream);
            TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);
            tarArchive.RootPath = sourceDirectory.Replace('\\', '/');
            if (tarArchive.RootPath.EndsWith("/"))
                tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);

            AddDirectoryFilesToTar(tarArchive, sourceDirectory, true);
            tarArchive.Close();
        }
예제 #25
0
        public static void Compress(string directory, string command, string destination)
        {
            if (!Directory.Exists(directory))
                return;

            var filesDirectory = Path.Combine(directory, command + "-files");
            var file = destination + ".oipkg";

            if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix) {
                var args = new StringBuilder();
                args.Append("\"" + file + "\" ");
                Directory
                    .GetFiles(directory, command + ".*")
                    .ToList()
                    .ForEach(x => args.Append("\"" + toRelative(x, directory) + "\" "));
                args.Append("\"" + toRelative(filesDirectory, directory) + "\"");
                run(directory, "tar", "-czf " + args.ToString());
                return;
            }

            var currentDirectory = Directory.GetCurrentDirectory();
            Directory.SetCurrentDirectory(directory);
            try
            {
                var outStream = File.Create(file);
                var gzoStream = new GZipOutputStream(outStream);
                var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);

                // Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
                // and must not end with a slash, otherwise cuts off first char of filename
                // This is scheduled for fix in next release
                tarArchive.RootPath = directory.Replace('\\', '/');
                if (tarArchive.RootPath.EndsWith("/"))
                    tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);

                Directory
                    .GetFiles(directory, command + ".*")
                    .ToList()
                    .ForEach(x => addFile(tarArchive, x));
                addDirectory(tarArchive, filesDirectory);

                tarArchive.Close();
            }
            catch(Exception ex)
            {
                Console.WriteLine("error|Exception during processing {0}", ex);
                throw;
            }
            finally
            {
                Directory.SetCurrentDirectory(currentDirectory);
            }
        }
예제 #26
0
		public void DelayedHeaderWriteNoData()
		{
			MemoryStream ms = new MemoryStream();
			Assert.AreEqual(0, ms.Length);
			
			using (GZipOutputStream outStream = new GZipOutputStream(ms)) {
				Assert.AreEqual(0, ms.Length);
			}
			
			byte[] data = ms.ToArray();

			Assert.IsTrue(data.Length > 0);
		}
예제 #27
0
        public void DoubleClose()
        {
            var memStream = new TrackedMemoryStream();
            var s = new GZipOutputStream(memStream);
            s.Finish();
            s.Close();
            s.Close();

            memStream = new TrackedMemoryStream();
            using (GZipOutputStream no2 = new GZipOutputStream(memStream)) {
                s.Close();
            }
        }
예제 #28
0
    public static byte[] Compress( byte[] bytesToCompress )
    {
        byte[] rebyte = null;
        MemoryStream ms = new MemoryStream();

        GZipOutputStream s = new GZipOutputStream(ms);
        s.Write( bytesToCompress , 0 , bytesToCompress.Length );
        s.Close();
        rebyte = ms.ToArray();

        ms.Close();
        return rebyte;
    }
예제 #29
0
파일: GZipUtil.cs 프로젝트: zeronely/View
 /// <summary>
 /// 压缩
 /// </summary>
 public static byte[] Compression(byte[] src)
 {
     if (IsGZip(src))
         return src;
     MemoryStream ms = new MemoryStream();
     GZipOutputStream gos = new GZipOutputStream(ms);
     gos.Write(src, 0, src.Length);
     gos.Close();
     // 由于从第五个字节开始的4个长度都是表示修改时间,因此可以强行设定
     byte[] result = ms.ToArray();
     result[4] = result[5] = result[6] = result[7] = 0x00;
     return result;
 }
예제 #30
0
        private const int COMPRESS_LEVEL = 7;// 0-9, 9 being the highest compression
        #endregion

        #region ICompressionProvider Members

        public byte[] Compress(byte[] data)
        {
            using (var outputStream = new MemoryStream())
            {
                using (var compressStream = new GZipOutputStream(outputStream))
                {
                    compressStream.SetLevel(COMPRESS_LEVEL);
                    compressStream.Write(data, 0, data.Length);
                    compressStream.Finish();
                    compressStream.Close();
                    return outputStream.ToArray();
                }
            }
        }
예제 #31
0
        public void CompressFile(string inFilePath, string outFilePath)
        {
            using (FileStream inFileStream =
                Util.IO.OpenFileStreamForReading(inFilePath)
                //new FileStream(inFilePath, FileMode.Open, FileAccess.Read)
                )
            {
                using (FileStream outFileStream = new FileStream(outFilePath, FileMode.Create, FileAccess.Write))
                {
                    using (var compressStream = new GZipOutputStream(outFileStream))
                    {
                        compressStream.SetLevel(COMPRESS_LEVEL);
                        byte[] buffer = new byte[BUFFER_SIZE];
                        ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(inFileStream, compressStream, buffer);
                    }
                }
            }

            /*
            using (FileStream inFileStream =
                Util.IO.OpenFileStreadForReading(inFilePath)
                //new FileStream(inFilePath, FileMode.Open, FileAccess.Read)
                )
            {
                using (FileStream outFileStream = new FileStream(outFilePath, FileMode.Create, FileAccess.Write))
                {
                    using (var compressStream = new GZipOutputStream(outFileStream))
                    {
                        compressStream.SetLevel(COMPRESS_LEVEL);
                        byte[] buffer = new byte[BUFFER_SIZE];
                        while(true)
                        {
                            int size = inFileStream.Read(buffer, 0, buffer.Length);
                            if (size > 0)
                            {
                                compressStream.Write(buffer, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        compressStream.Finish();
                        compressStream.Close();
                    }
                }
            }
             */            
        }
예제 #32
0
        public void Process(BundleContext context, BundleResponse response)
        {
            var contentBytes = new UTF8Encoding().GetBytes(response.Content);

            var outputStream = new MemoryStream();
            var gzipOutputStream = new GZipOutputStream(outputStream);
            gzipOutputStream.Write(contentBytes, 0, contentBytes.Length);

            var outputBytes = outputStream.GetBuffer();
            response.Content = Convert.ToBase64String(outputBytes);

            // NOTE: this part is broken -> http://stackoverflow.com/a/11353652
            context.HttpContext.Response.Headers["Content-Encoding"] = "gzip";
            response.ContentType = _contentType;
        }
예제 #33
0
        /// <summary>
        /// Compress the <paramref name="inStream">input stream</paramref> sending
        /// result data to <paramref name="outStream">output stream</paramref>
        /// </summary>
        /// <param name="inStream">The readable stream to compress.</param>
        /// <param name="outStream">The output stream to receive the compressed data.</param>
        /// <param name="isStreamOwner">Both streams are closed on completion if true.</param>
        /// <param name="level">Block size acts as compression level (1 to 9) with 1 giving
        /// the lowest compression and 9 the highest.</param>
        public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int level)
        {
            if (inStream == null || outStream == null)
            {
                throw new Exception("Null Stream");
            }

            try {
                using (GZipOutputStream bzipOutput = new GZipOutputStream(outStream, level)) {
                    bzipOutput.IsStreamOwner = isStreamOwner;
                    Core.StreamUtils.Copy(inStream, bzipOutput, new byte[4096]);
                }
            } finally {
                if (isStreamOwner)
                {
                    // outStream is closed by the GZipOutputStream if stream owner
                    inStream.Close();
                }
            }
        }
예제 #34
0
 static int Main(string[] args)
 {
     try
     {
         byte[] buf = new byte[1024];
         int    n;
         using (Stream input = Console.OpenStandardInput())
             using (Stream output = new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(Console.OpenStandardOutput()))
                 while ((n = input.Read(buf, 0, buf.Length)) != 0)
                 {
                     output.Write(buf, 0, n);
                 }
         return(0);
     }
     catch (Exception e)
     {
         Console.Error.WriteLine("Error: " + e.Message);
         return(1);
     }
 }
예제 #35
0
 public int OnExecute(IConsole console)
 {
     try
     {
         using (var istm = Util.OpenInputStream(InputFile))
             using (var ostm = Util.OpenOutputStream(OutputFile, true))
             {
                 using (var ozstm = new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(ostm))
                 {
                     ozstm.SetLevel(Level);
                     istm.CopyTo(ozstm);
                 }
             }
     }
     catch (Exception e)
     {
         console.Error.WriteLine($"failed gzip compression:{e}");
         return(1);
     }
     return(0);
 }
예제 #36
0
파일: GZip.cs 프로젝트: intvsteve/VINTage
        /// <summary>
        /// Compress the <paramref name="inStream">input stream</paramref> sending
        /// result data to <paramref name="outStream">output stream</paramref>
        /// </summary>
        /// <param name="inStream">The readable stream to compress.</param>
        /// <param name="outStream">The output stream to receive the compressed data.</param>
        /// <param name="isStreamOwner">Both streams are closed on completion if true.</param>
        /// <param name="bufferSize">Deflate buffer size, minimum 512</param>
        /// <param name="level">Deflate compression level, 0-9</param>
        /// <exception cref="ArgumentNullException">Input or output stream is null</exception>
        /// <exception cref="ArgumentOutOfRangeException">Buffer Size is smaller than 512</exception>
        /// <exception cref="ArgumentOutOfRangeException">Compression level outside 0-9</exception>
        public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int bufferSize = 512, int level = 6)
        {
            if (inStream == null)
            {
                throw new ArgumentNullException("inStream", "Input stream is null");
            }

            if (outStream == null)
            {
                throw new ArgumentNullException("outStream", "Output stream is null");
            }

            if (bufferSize < 512)
            {
                throw new ArgumentOutOfRangeException("bufferSize", "Deflate buffer size must be >= 512");
            }

            if (level < Zip.Compression.Deflater.NO_COMPRESSION || level > Zip.Compression.Deflater.BEST_COMPRESSION)
            {
                throw new ArgumentOutOfRangeException("level", "Compression level must be 0-9");
            }

            try
            {
                using (GZipOutputStream gzipOutput = new GZipOutputStream(outStream, bufferSize))
                {
                    gzipOutput.SetLevel(level);
                    gzipOutput.IsStreamOwner = isStreamOwner;
                    Core.StreamUtils.Copy(inStream, gzipOutput, new byte[bufferSize]);
                }
            }
            finally
            {
                if (isStreamOwner)
                {
                    // outStream is closed by the GZipOutputStream if stream owner
                    inStream.Dispose();
                }
            }
        }
예제 #37
0
 public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, GZipFile.CodeProgress progress)
 {
     if (inStream == null || outStream == null)
     {
         throw new Exception("Null Stream");
     }
     try
     {
         using (GZipOutputStream gZipOutputStream = new GZipOutputStream(outStream))
         {
             gZipOutputStream.IsStreamOwner = isStreamOwner;
             StreamUtils.Copy(inStream, gZipOutputStream, new byte[4096], progress);
         }
     }
     finally
     {
         if (isStreamOwner)
         {
             inStream.Close();
         }
     }
 }
예제 #38
0
 public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int level)
 {
     if (inStream == null || outStream == null)
     {
         throw new Exception("Null Stream");
     }
     try
     {
         using (GZipOutputStream gZipOutputStream = new GZipOutputStream(outStream, level))
         {
             gZipOutputStream.IsStreamOwner = isStreamOwner;
             StreamUtils.Copy(inStream, gZipOutputStream, new byte[4096]);
         }
     }
     finally
     {
         if (isStreamOwner)
         {
             inStream.Dispose();
         }
     }
 }
예제 #39
0
        public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, GZipFile.CodeProgress progress)
        {
            if (inStream == null || outStream == null)
            {
                throw new Exception("Null Stream");
            }

            try
            {
                using (GZipOutputStream bzipOutput = new GZipOutputStream(outStream))
                {
                    bzipOutput.IsStreamOwner = isStreamOwner;;
                    ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(inStream, bzipOutput, new byte[4096], progress);
                }
            }
            finally
            {
                if (isStreamOwner)
                {
                    // outStream is closed by the GZipOutputStream if stream owner
                    inStream.Close();
                }
            }
        }