Пример #1
0
        static public void ArchiveFile(string inFilePath, string inFilePath2, string zipArchive)
        {
            using (var fileStream = File.OpenRead(inFilePath))
                using (var fileStream2 = File.OpenRead(inFilePath2))
                {
                    using (var destinationFileStream = File.Create(zipArchive))
                    {
                        using (var zipStream = new GZipStream(destinationFileStream, CompressionMode.Compress))
                        {
                            var singleByte = fileStream.ReadByte();
                            do
                            {
                                zipStream.WriteByte((byte)singleByte);
                                singleByte = fileStream.ReadByte();
                            } while (singleByte != -1);

                            singleByte = fileStream2.ReadByte();
                            do
                            {
                                zipStream.WriteByte((byte)singleByte);
                                singleByte = fileStream2.ReadByte();
                            } while (singleByte != -1);
                        }
                    }
                }
        }
Пример #2
0
        private string EncodeBase64(string compression, uint[,] data, int width, int height)
        {
            Stream stream;
            var    memStream = new MemoryStream(width * height * sizeof(uint));
            uint?  checksum  = null;

            switch (compression)
            {
            case "gzip":
                stream = new GZipStream(memStream, CompressionMode.Compress, true);
                break;

            /*case "zlib":
             *  memStream.WriteByte(0x78);
             *  memStream.WriteByte(0x9C);
             *  stream = new DeflateStream(memStream, CompressionMode.Compress, true);
             *  checksum = 0;
             *  break;*/
            case null:
                stream = memStream;
                break;

            default:
                throw new Exception($"Layer data: {compression} compression is not supported.");
            }

            int arrayX = data.GetLength(0);
            int arrayY = data.GetLength(1);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    uint uid = 0;
                    if (x < arrayX && y < arrayY)
                    {
                        uid = data[x, y];
                    }
                    stream.WriteByte((byte)((uid >> 0) & 0xFF));
                    stream.WriteByte((byte)((uid >> 8) & 0xFF));
                    stream.WriteByte((byte)((uid >> 16) & 0xFF));
                    stream.WriteByte((byte)((uid >> 24) & 0xFF));
                }
            }
            stream.Flush();
            if (memStream != stream)
            {
                stream.Close();
            }
            if (checksum.HasValue)
            {
                memStream.WriteByte((byte)((checksum >> 0) & 0xFF));
                memStream.WriteByte((byte)((checksum >> 8) & 0xFF));
                memStream.WriteByte((byte)((checksum >> 16) & 0xFF));
                memStream.WriteByte((byte)((checksum >> 24) & 0xFF));
            }
            return(Convert.ToBase64String(memStream.GetBuffer(), 0, (int)memStream.Length));
        }
Пример #3
0
        /// <summary>
        /// Wraps the given stream in a compression stream.
        /// </summary>
        /// <param name="output">Stream to wrap.</param>
        /// <returns>Compression stream to which data can be written.</returns>
        public static Stream CompressStream(Stream output)
        {
            Stream result = new GZipStream(output, CompressionMode.Compress);

            result.WriteByte(0xff & (MagicNumber >> 24));
            result.WriteByte(0xff & (MagicNumber >> 16));
            result.WriteByte(0xff & (MagicNumber >> 8));
            result.WriteByte(0xff & (MagicNumber));
            return(result);
        }
Пример #4
0
        static void ArchiveFile(DirectoryInfo archiveDir, FileInfo fileToArchive)
        {
            // Function tries to open the file, in case of IOException it tries it again after a second
            Boolean knockKnock = true;

            while (knockKnock)
            {
                try
                {
                    fileToArchive.OpenRead();
                    knockKnock = false;
                    break;
                }
                catch (IOException e)
                {
                    Console.WriteLine(e.Message);
                    Thread.Sleep(1000);
                }
            }
            FileStream input      = fileToArchive.OpenRead();
            FileStream output     = File.Create(archiveDir.FullName + @"\" + fileToArchive.Name + ".gz");
            GZipStream Compressor = new GZipStream(output, CompressionMode.Compress);
            int        b          = input.ReadByte();

            while (b != -1)
            {
                Compressor.WriteByte((byte)b);
                b = input.ReadByte();
            }
            Compressor.Close();
            input.Close();
            output.Close();
        }
Пример #5
0
 //Comprimir archivo en formato gz,zip,etc
 public void comprimir(string ruta, string nombre_comprimido_extension)
 {
     try
     {
         using (FileStream fs = new FileStream(ruta, FileMode.Open, FileAccess.Read))                                      //crea un stream para abrir el archivo en modo lectura
         {
             using (FileStream fsc = new FileStream(nombre_comprimido_extension, FileMode.OpenOrCreate, FileAccess.Write)) //crea un stream para crear el archivo y escribir sobre el
             {
                 using (GZipStream gz = new GZipStream(fsc, CompressionMode.Compress))
                 {
                     int i = fs.ReadByte();
                     while (i != -1)
                     {
                         gz.WriteByte((byte)i);
                         i = fs.ReadByte();
                     }
                     gz.Close();
                 }
                 fsc.Close();
             }
             fs.Close();
         }
     }
     catch (Exception excepccion)
     {
         System.Windows.MessageBox.Show("Error, consulte a su Administrador de Sistema");
     }
 }
Пример #6
0
        // Поток архивации
        static void VPotok(long byteCounters, string name, int count, string reName = null)
        {
            FileStream fromStream = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read);

            fromStream.Position = byteCounters * (count - 1);
            FileStream targetFile = File.Open(string.Format(name + ".gz{0}", count), FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
            GZipStream gzipStream = new GZipStream(targetFile, CompressionMode.Compress, true);

            while (fromStream.CanRead && byteCounters > 0)
            {
                byteCounters--;
                gzipStream.WriteByte((byte)fromStream.ReadByte());
            }

            fromStream.Dispose();
            gzipStream.Dispose();
            targetFile.Dispose();
            fromStream.Close();
            gzipStream.Close();
            targetFile.Close();
            _potokov--;
            if (_potokov == 0)
            {
                Sborka(name + ".gz", reName);
            }
        }
Пример #7
0
        private void compressToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string   selectedFile   = listView1.SelectedItems[0].Text;
            FileInfo fileToCompress = new FileInfo(currentDir + "\\" + selectedFile);

            if (selectedFile.Substring(selectedFile.LastIndexOf('.')) != ".gz")
            {
                using (FileStream input = fileToCompress.OpenRead())
                {
                    using (FileStream output = File.Create(currentDir + "\\" + fileToCompress.Name + ".gz"))
                    {
                        using (GZipStream Compressor = new GZipStream(output, CompressionMode.Compress))
                        {
                            int b = input.ReadByte();
                            while (b != -1)
                            {
                                Compressor.WriteByte((byte)b);
                                b = input.ReadByte();
                            }
                        }
                    }
                }
                try
                {
                    fileToCompress.Delete();
                }
                catch (Exception exc) { }
            }
        }
        public static void CompressFile(string inFilename, string outFilename)
        {
            try
            {
                var sourceFile = File.Open(inFilename, FileMode.Open);
                var destFile   = File.Create(outFilename);
                var compStream = new GZipStream(destFile, CompressionMode.Compress);

                var theByte = sourceFile.ReadByte();
                while (theByte != -1)
                {
                    compStream.WriteByte((byte)theByte);
                    theByte = sourceFile.ReadByte();
                }

                compStream.Close();
                sourceFile.Close();
                destFile.Close();

                Console.WriteLine($"\"{inFilename}\" архивирован в \"{outFilename}\".");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Произошла ошибка: {ex.Message}");
            }
        }
Пример #9
0
        private static void FindNameFile(string fileName)
        {
            FileStream source = null;
            FileStream destin = File.Create(@"D:\FindFolder.zip");
            string     name   = null;
            FileInfo   file;

            foreach (var value in Directory.EnumerateFiles(@"D:\ITEA", fileName, SearchOption.AllDirectories))
            {
                try
                {
                    file = new FileInfo(value);
                    name = new FileInfo(value).FullName;
                    Console.WriteLine(file.FullName + " " + file.Attributes + file.CreationTime);
                }
                catch
                {
                    continue;
                }
            }

            source = File.OpenRead(name);
            GZipStream compres = new GZipStream(destin, CompressionMode.Compress);
            int        theByte = source.ReadByte();

            while (theByte != -1)
            {
                compres.WriteByte((byte)theByte);
                theByte = source.ReadByte();
            }
            compres.Close();
        }
Пример #10
0
        static void Main(string[] args)
        {
            NSApplication.Init();

            Test.EnsureLinker(true);

            bool gzip = false;

            try {
                GZipStream gz = new GZipStream(Stream.Null, CompressionMode.Compress);
                gz.WriteByte(0);
                gz.Close();
                gzip = true;
            }
            catch {
            }
            Test.Log.WriteLine("{0}\t{1}", gzip ? "[PASS]" : "[FAIL]", "GZipStream support");

            string path    = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            bool   bundled = File.Exists(Path.Combine(path, "libMonoPosixHelper.dylib"));

            Test.Log.WriteLine("{0}\t{1}", bundled ? "[PASS]" : "[FAIL]", "MonoPosixHelper present in bundle");

            Test.Terminate();
        }
Пример #11
0
 public static void DownloadIanaFile(string cacheFile, string sourceUri = "http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry")
 {
     using (var f = File.Open(cacheFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {
         try
         {
             using (WebClient client = new WebClient())
             {
                 using (Stream stream = client.OpenRead(sourceUri))
                 {
                     using (GZipStream output = new GZipStream(f, CompressionMode.Compress))
                     {
                         int i = 0;
                         while ((i = stream.ReadByte()) > 0)
                         {
                             output.WriteByte((byte)i);
                         }
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             f.Close();
             File.Delete(cacheFile);
             throw ex;
         }
     }
 }
Пример #12
0
        private static void ListenTo(TcpClient cl)
        {
            Console.WriteLine("" + cl.Client.RemoteEndPoint + " conectado");
            Stream stream = new GZipStream(cl.GetStream(), CompressionLevel.Optimal);

            using (BinaryWriter writer = new BinaryWriter(stream))
                try
                {
                    while (true)
                    {
                        stream.WriteByte(1);
                        stream.Flush();

                        if (bytes != null)
                        {
                            writer.Write(bytes.Length);
                            writer.Write(bytes);
                            writer.Flush();
                        }

                        Thread.Sleep(16);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("" + cl.Client.RemoteEndPoint + " desconectado (" + e.Message + ")");
                    try { cl.Close(); } catch { }
                }
        }
Пример #13
0
        private void buttonCompress_Click(object sender, EventArgs e)
        {
            FileStream sourceFile = File.OpenRead(@"C:\TEST\MCTS(rgb)_512.jpg");
            FileStream destFile   = File.Create(@"C:\TEST\MCTS(rgb)_512.gz");

            gzip = new GZipStream(destFile, CompressionMode.Compress);

            int theByte = sourceFile.ReadByte();

            while (theByte != -1)
            {
                gzip.WriteByte((byte)theByte);
                theByte = sourceFile.ReadByte();
            }

            gzip.Flush();
            gzip.Close();
            gzip.Dispose();

            destFile.Close();
            destFile.Dispose();

            sourceFile.Close();
            sourceFile.Dispose();
            MessageBox.Show("Done");
        }
Пример #14
0
        // WriteZip() – save data to zip file
        // method takes data (info about computers) as parameter
        public void WriteZip(IEnumerable <Computer> computerList)
        {
            StringBuilder stb = new StringBuilder(string.Empty);

            if (computerList != null)
            {
                foreach (var item in computerList)
                {
                    stb.Append($"{item.Cores}\t{item.Frequency}\t{item.Memory}\t{item.Hdd}\n");
                }
            }

            using (MemoryStream memoryStream = new MemoryStream(Encoding.Default.GetBytes(stb.ToString().TrimEnd('\n'))))
            {
                int readWriteByte = memoryStream.ReadByte();
                using (var zipStream = new GZipStream(new FileStream(Path.Combine(CurrentPath, CurrentFile.Replace(".txt", ".gz")), FileMode.Create), CompressionMode.Compress))
                {
                    while (readWriteByte != -1)
                    {
                        zipStream.WriteByte((byte)readWriteByte);
                        readWriteByte = memoryStream.ReadByte();
                    }
                }
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            //Создание файла и запись в него данных
            var fieStream = File.Open(@"D:\test_zip_1.txt", FileMode.OpenOrCreate);

            //у StreamWriter`а немножко поудобнее запись, чем у стандартного
            //FileStream`а, который нам любезно возвращается когда файл создается.
            //FileStream может читать и писать, но из него мы всегда можем сделать более удобные StreamWriter и StreamReader
            using (StreamWriter writter = new StreamWriter(fieStream))
            {
                writter.WriteLine("Hello, Roman from Zip");
                //Вот после операторной скобки заароются writter и fieStream
            }
            //Создание архива
            FileStream destination = File.Create(@"D:\archive_zip.zip");

            //Создание компрессора - используется паттерн Дкоратор.
            //Назначение этого паттерна - добавить новые обязанности объекту.
            GZipStream compressor = new GZipStream(destination, CompressionMode.Compress);

            using (var fieStream2 = File.Open(@"D:\test_zip_1.txt", FileMode.OpenOrCreate))
            {
                //Заполнение архива информацией из файла - тут лучше применить do while!!!!!, смотри пример 003_Zip_Decompression
                int theByte = fieStream2.ReadByte();
                while (theByte != -1)
                {
                    compressor.WriteByte((byte)theByte);
                    theByte = fieStream2.ReadByte();
                }
            }

            //Удвление компрессора
            compressor.Close();
        }
Пример #16
0
 public static void ArchiveFile(DirectoryInfo archiveDir, FileInfo fileToArchive)
 {
     try
     {
         FileStream input      = File.Open(fileToArchive.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
         FileStream output     = File.Create(archiveDir.FullName + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileToArchive.Name + ".gz");
         GZipStream Compressor = new GZipStream(output, CompressionMode.Compress);
         int        b          = input.ReadByte();
         while (b != -1)
         {
             Compressor.WriteByte((byte)b);
             b = input.ReadByte();
         }
         Compressor.Close();
         input.Close();
         output.Close();
     }
     catch (UnauthorizedAccessException)
     {
         MessageBox.Show("You don't have the rights to Compress this file.");
     }
     catch (Exception)
     {
         MessageBox.Show("Oops, something went wrong. You probably should go home now.");
     }
 }
        private void ArchiveFile(DirectoryInfo dirToArchive, FileInfo fileToArchive)
        {
            archiveDirectoryInfo = new DirectoryInfo(dirToArchive + "\\Archives");
            Directory.CreateDirectory(archiveDirectoryInfo.ToString());
            string     fullPath     = dirToArchive.ToString() + fileToArchive.ToString();
            FileInfo   fullpathInfo = new FileInfo(fullPath);
            FileStream input        = fullpathInfo.OpenRead();
            FileStream output       = File.Create(
                archiveDirectoryInfo.FullName +
                @"\" +
                Path.GetFileNameWithoutExtension(fileToArchive.ToString()) +
                "_archive" +
                DateTime.Now.ToString("_yyyy-MM-dd-hh-mm-ss") +
                fileToArchive.Extension +
                ".gz"
                );
            GZipStream Compressor = new GZipStream(output, CompressionMode.Compress);
            int        byteInfo   = input.ReadByte();

            while (byteInfo != -1)
            {
                Compressor.WriteByte((byte)byteInfo);

                byteInfo = input.ReadByte();
            }
            Compressor.Close();
            input.Close();
            output.Close();
        }
Пример #18
0
        public void ShouldReadStreamWrittenByMultipleWriters()
        {
            var memory = new MemoryStream();

            using (var stream = new GZipStream(memory, CompressionMode.Compress))
            {
                stream.WriteByte(5);
            }
            var intermediate = memory.GetBuffer();

            memory = new MemoryStream();
            memory.Write(intermediate, 0, intermediate.Length);
            using (var stream = new GZipStream(memory, CompressionMode.Compress))
            {
                stream.WriteByte(1);
            }
            memory = new MemoryStream(memory.GetBuffer());
            var actual = new Byte[2];

            using (var stream = new GZipStream(memory, CompressionMode.Decompress))
            {
                stream.Read(actual, 0, 2);
            }
            Assert.AreEqual(new byte[] { 5, 1 }, actual);
        }
Пример #19
0
        public static bool CompressToZip(string filePath, string zipFileName)
        {
            var file = new FileInfo(filePath);

            if (!file.Exists)
            {
                return(false);
            }

            if (Path.HasExtension(zipFileName))
            {
                Path.ChangeExtension(zipFileName, ".zip");
            }
            else
            {
                zipFileName += ".zip";
            }
            string path = file.DirectoryName + zipFileName;

            FileStream source     = File.Open(filePath, FileMode.Open);
            GZipStream compressor = new GZipStream(File.Create(path), CompressionMode.Compress);
            int        theByte    = source.ReadByte();

            while (theByte != -1)
            {
                compressor.WriteByte((byte)theByte);
                theByte = source.ReadByte();
            }
            compressor.Close();
            source.Close();
            return(true);
        }
Пример #20
0
 private void BtnArchivin_Click(object sender, EventArgs e)
 {
     btnArchivin.Text = "Архивация...";
     if (path.Length == 0)
     {
         MessageBox.Show("файл не найден");
     }
     else
     {
         for (int i = 0; i < path.Length; i++)
         {
             FileStream fileStream  = File.OpenRead(path[i]);
             FileStream fileStream2 = File.Create(path[i] + ".zip");
             GZipStream gZipStream  = new GZipStream(fileStream2, CompressionMode.Compress);
             int        bt          = fileStream.ReadByte();
             while (bt != -1)
             {
                 gZipStream.WriteByte((byte)bt);
                 bt = fileStream.ReadByte();
             }
             gZipStream.Close();
             listBox1.Items.Add("Заархивировано");
         }
     }
     btnArchivin.Text = "Заархивировано";
 }
Пример #21
0
        public override async Task <string> ProcessMessageAsync(KinesisEvent request)
        {
            LogInfo($"Received {request.Records.Count:N0} Kinesis Stream records");

            // combine all records and compress them for storage
            var originalSize = request.Records.Sum(record => record.Kinesis.Data.Length);

            using var eventStream = new MemoryStream();
            using (var gzipStream = new GZipStream(eventStream, CompressionLevel.Optimal, leaveOpen: true)) {
                foreach (var record in request.Records)
                {
                    record.Kinesis.Data.CopyTo(gzipStream);
                    gzipStream.WriteByte((byte)'\n');
                }
            }
            eventStream.Position = 0;
            var compressedSize = eventStream.Length;

            LogInfo($"Compressed {request.Records.Count:N0} Kinesis Stream records (original: {originalSize:N0} bytes, stored: {compressedSize:N0} bytes)");

            // store event in S3
            var arrivalTime = request.Records.First().Kinesis.ApproximateArrivalTimestamp;
            var s3Key       = $"{arrivalTime.Year:0000}/{arrivalTime.Month:00}/{arrivalTime.Hour:00}/{request.Records.First().EventId.Split(':', 2)[1]}.gz";
            await _s3Client.PutObjectAsync(new PutObjectRequest {
                BucketName  = _bucketName,
                Key         = s3Key,
                InputStream = eventStream
            });

            LogInfo($"Stored {s3Key}");
            return("Ok");
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Enter file name");
            string path = Console.ReadLine();

            using (FileStream fs = File.OpenRead(@path))
            {
                byte[]       b    = new byte[1024];
                UTF8Encoding temp = new UTF8Encoding(true);
                while (fs.Read(b, 0, b.Length) > 0)
                {
                    Console.WriteLine(temp.GetString(b));
                }

                Console.WriteLine("zip?");
                Console.ReadKey();

                FileStream destination = File.Create(@"archive.zip");

                GZipStream compressor = new GZipStream(destination, CompressionMode.Compress);

                int theByte = fs.ReadByte();
                while (theByte != -1)
                {
                    compressor.WriteByte((byte)theByte);
                    theByte = fs.ReadByte();
                }

                compressor.Close();
            }
            Console.ReadKey();
        }
Пример #23
0
        public void ShouldReadStreamWrittenSingleWriter()
        {
            var memory = new MemoryStream();

            using (var stream = new GZipStream(memory, CompressionMode.Compress))
            {
                stream.WriteByte(5);
                stream.WriteByte(42);
            }
            memory = new MemoryStream(memory.GetBuffer());
            var actual = new Byte[2];

            using (var stream = new GZipStream(memory, CompressionMode.Decompress))
            {
                stream.Read(actual, 0, 2);
            }
            Assert.AreEqual(new byte[] { 5, 42 }, actual);
        }
Пример #24
0
        public void Save()
        {
            try
            {
                byte[] saveblocks = new byte[blocks.Length];
                blocks.CopyTo(saveblocks, 0);
                for (int i = 0; i < saveblocks.Length; i++)
                {
                    switch (saveblocks[i])
                    {
                    case Blocks.unflood:
                        saveblocks[i] = Blocks.ConvertType(saveblocks[i]);
                        break;

                    default:
                        break;
                    }
                }

                GZipStream gzout = new GZipStream(new FileStream("maps/" + filename, FileMode.OpenOrCreate), CompressionMode.Compress);
                gzout.Write(BitConverter.GetBytes(0xebabefac), 0, 4);
                gzout.Write(BitConverter.GetBytes(width), 0, 2);
                gzout.Write(BitConverter.GetBytes(height), 0, 2);
                gzout.Write(BitConverter.GetBytes(depth), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawnx), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawny), 0, 2);
                gzout.Write(BitConverter.GetBytes(spawnz), 0, 2);
                gzout.WriteByte(this.srotx);
                gzout.WriteByte(this.sroty);
                gzout.Write(saveblocks, 0, saveblocks.Length);

                //gzout.BaseStream.Close();
                gzout.Close();
                Program.server.logger.log("Level \"" + this.name + "\" saved");
            }
            catch (Exception e)
            {
                Program.server.logger.log("Error occurred while saving map", Logger.LogType.Error);
                Program.server.logger.log(e);
            }
        }
Пример #25
0
        static void CompressFile(string inFilename,
                                 string outFilename)
        {
            GZipStream compStream =
                new GZipStream(destFile, CompressionMode.Compress);
            int theByte - sourceFile.ReadByte();

            while (theByte != -1)
            {
                compStream.WriteByte((byte)theByte); theByte = sourceFile.ReadByte();
            }
        }
Пример #26
0
            void SaveLvl(Stream stream)
            {
                using (Stream gs = new GZipStream(stream, CompressionMode.Compress, true))
                {
                    byte[] header = new byte[16];
                    BitConverter.GetBytes(1874).CopyTo(header, 0);
                    gs.Write(header, 0, 2);

                    BitConverter.GetBytes(width).CopyTo(header, 0);
                    BitConverter.GetBytes(length).CopyTo(header, 2);
                    BitConverter.GetBytes(height).CopyTo(header, 4);

                    gs.Write(header, 0, header.Length);
                    gs.Write(blocks, 0, blocks.Length);

                    // Write out new blockdefinitions data
                    gs.WriteByte(0xBD);
                    int index = 0;
                    for (int y = 0; y < chunksY; y++)
                    {
                        for (int z = 0; z < chunksZ; z++)
                        {
                            for (int x = 0; x < chunksX; x++)
                            {
                                byte[] chunk = customBlocks[index];
                                if (chunk == null)
                                {
                                    gs.WriteByte(0);
                                }
                                else
                                {
                                    gs.WriteByte(1);
                                    gs.Write(chunk, 0, chunk.Length);
                                }
                                index++;
                            }
                        }
                    }
                }
            }
Пример #27
0
        private void AddInfoToArchive()
        {
            bool us = watchText.MainFileStream.CanRead;

            watchText.MainFileStream.Position = 0;
            int theByte = watchText.MainFileStream.ReadByte();

            while (theByte != -1)
            {
                compressor.WriteByte((byte)theByte);
                theByte = watchText.MainFileStream.ReadByte();
            }
        }
Пример #28
0
        private static void ArchiveFile(DirectoryInfo archiveDir, FileInfo fileToArchive)
        {
            FileStream input = fileToArchive.OpenRead(); FileStream output = File.Create(archiveDir.FullName + @"" + fileToArchive.Name + ".gz");
            GZipStream Compressor = new GZipStream(output, CompressionMode.Compress);
            int        b          = input.ReadByte(); while (b != -1)

            {
                Compressor.WriteByte((byte)b);

                b = input.ReadByte();
            }
            Compressor.Close(); input.Close(); output.Close();
        }
Пример #29
0
        static void CompressFile(string inFilename, string outFilename)
        {
            FileStream sourceFile = File.OpenRead(inFilename);
            FileStream destFile   = File.Create(outFilename);
            GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);
            int        theByte    = sourceFile.ReadByte();

            while (theByte != -1)
            {
                compStream.WriteByte((byte)theByte);
                theByte = sourceFile.ReadByte();
            }
            compStream.Close();
        }
 internal static void Compress(string pathFrom, string pathInto)
 {
     using (FileStream fsr = File.OpenRead(pathFrom))
         using (FileStream file = File.Create(pathInto))
             using (GZipStream gZipStream = new GZipStream(file, CompressionMode.Compress))
             {
                 int oneByte = 0;
                 do
                 {
                     oneByte = fsr.ReadByte();
                     gZipStream.WriteByte((byte)oneByte);
                 }while (oneByte != -1);
             }
 }
Пример #31
0
        public void Zlib_GZipStream_ByteByByte_CheckCrc()
        {
            // select the name of the zip file
            string FileToCompress = System.IO.Path.Combine(TopLevelDir, "Zlib_GZipStream_ByteByByte.dat");
            Assert.IsFalse(System.IO.File.Exists(FileToCompress), "The temporary zip file '{0}' already exists.", FileToCompress);
            byte[] working = new byte[WORKING_BUFFER_SIZE];
            int n = -1;

            int sz = this.rnd.Next(21000) + 15000;
            TestContext.WriteLine("  Creating file: {0} sz({1})", FileToCompress, sz);
            CreateAndFillFileText(FileToCompress, sz);

            System.IO.FileInfo fi1 = new System.IO.FileInfo(FileToCompress);
            int crc1 = DoCrc(FileToCompress);

            // four trials, all combos of FileName and Comment null or not null.
            for (int k = 0; k < 4; k++)
            {
                string CompressedFile = String.Format("{0}-{1}.compressed", FileToCompress, k);

                using (Stream input = File.OpenRead(FileToCompress))
                {
                    using (FileStream raw = new FileStream(CompressedFile, FileMode.Create))
                    {
                        using (GZipStream compressor =
                               new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
                        {
                            // FileName is optional metadata in the GZip bytestream
                            if (k % 2 == 1)
                                compressor.FileName = FileToCompress;

                            // Comment is optional metadata in the GZip bytestream
                            if (k > 2)
                                compressor.Comment = "Compressing: " + FileToCompress;

                            byte[] buffer = new byte[1024];
                            n = -1;
                            while (n != 0)
                            {
                                if (n > 0)
                                {
                                    for (int i=0; i < n; i++)
                                        compressor.WriteByte(buffer[i]);
                                }

                                n = input.Read(buffer, 0, buffer.Length);
                            }
                        }
                    }
                }

                System.IO.FileInfo fi2 = new System.IO.FileInfo(CompressedFile);

                Assert.IsTrue(fi1.Length > fi2.Length, String.Format("Compressed File is not smaller, trial {0} ({1}!>{2})", k, fi1.Length, fi2.Length));


                // decompress twice:
                // once with System.IO.Compression.GZipStream and once with Alienlab.Zlib.GZipStream
                for (int j = 0; j < 2; j++)
                {
                    using (var input = System.IO.File.OpenRead(CompressedFile))
                    {

                        Stream decompressor = null;
                        try
                        {
                            switch (j)
                            {
                            case 0:
                                decompressor = new Alienlab.Zlib.GZipStream(input, CompressionMode.Decompress, true);
                                break;
                            case 1:
                                decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress, true);
                                break;
                            }

                            string DecompressedFile =
                                String.Format("{0}.{1}.decompressed", CompressedFile, (j == 0) ? "Ionic" : "BCL");

                            TestContext.WriteLine("........{0} ...", System.IO.Path.GetFileName(DecompressedFile));

                            using (var s2 = System.IO.File.Create(DecompressedFile))
                            {
                                n = -1;
                                while (n != 0)
                                {
                                    n = decompressor.Read(working, 0, working.Length);
                                    if (n > 0)
                                        s2.Write(working, 0, n);
                                }
                            }

                            int crc2 = DoCrc(DecompressedFile);
                            Assert.AreEqual<Int32>(crc1, crc2);

                        }
                        finally
                        {
                            if (decompressor as Alienlab.Zlib.GZipStream != null)
                            {
                                var gz = (Ionic.Zlib.GZipStream) decompressor;
                                gz.Close(); // sets the final CRC
                                Assert.AreEqual<Int32>(gz.Crc32, crc1);
                            }

                            if (decompressor != null)
                                decompressor.Dispose();
                        }
                    }
                }
            }
        }