Пример #1
0
 private byte[] Decompress(byte[] combinedData)
 {
     using var compressedData   = new MemoryStream(combinedData);
     using var uncompressedData = new MemoryStream();
     BZip2.Decompress(compressedData, uncompressedData, true);
     return(uncompressedData.ToArray());
 }
Пример #2
0
        public void CompressTest1()
        {
            for (int i = 0; i < 1000; i++)
            {
                byte[] buffer = new byte[1000];

                var rnd = new Random();
                rnd.NextBytes(buffer);


                var deflated = BZip2.Compress(buffer);
                var inflated = BZip2.Decompress(deflated);

                Assert.AreEqual(buffer.Length, inflated.Length);

                //for (var i = 0; i < buffer.Length; i++)
                //{
                //    Assert.AreEqual(buffer[i], inflated[i]);
                //}

                if (i % 100 == 0)
                {
                    Console.WriteLine(MemInfo.GetCurProcessMem());
                }
            }
        }
Пример #3
0
    //使用BZIP解压<--单个-->文件的方法
    public static bool UnBzipFile(string zipfilename, string unzipfilename)
    {
        bool blResult;//表示解压是否成功的返回结果

        //为压缩文件创建文件流实例,作为解压方法的输入流参数
        using (FileStream zipFile = File.OpenRead(zipfilename))
        {
            //为目标文件创建文件流实例,作为解压方法的输出流参数
            using (FileStream destFile = File.Open(unzipfilename, FileMode.Create))
            {
                try
                {
                    BZip2.Decompress(zipFile, destFile, true);//解压文件
                    blResult = true;
                }
                catch (Exception ee)
                {
                    Console.WriteLine(ee.Message);
                    blResult = false;
                }
                destFile.Close(); //关闭目标文件流
                zipFile.Close();  //关闭压缩文件流
                return(blResult);
            }
        }
    }
Пример #4
0
        /// <summary>
        /// Unpacks a plugin package.
        /// </summary>
        /// <param name="path">The path to the package</param>
        /// <returns>The path to the unpacked DLL file of the plugin</returns>
        private static string Unpack(string path)
        {
            try
            {
                string suffix = Path.GetRandomFileName();
                suffix = "_" + suffix.Replace(".", "");
                string bz2File = path;
                string tarFile = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + ".tar");
                string dest    = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + suffix);

                U.L(LogLevel.Debug, "PLUGIN", "Decompressing " + path);
                BZip2.Decompress(File.OpenRead(bz2File), File.Create(tarFile), true);

                Stream     inStream = File.OpenRead(tarFile);
                TarArchive archive  = TarArchive.CreateInputTarArchive(inStream, TarBuffer.DefaultBlockFactor);
                Directory.CreateDirectory(dest);
                archive.ExtractContents(dest);
                archive.Close();
                inStream.Close();
                File.Delete(tarFile);

                return(Path.Combine(dest, Path.GetFileNameWithoutExtension(path) + ".dll"));
            }
            catch (Exception e)
            {
                U.L(LogLevel.Error, "PLUGIN", "Could not unpack plugin package: " + e.Message);
                return(null);
            }
        }
Пример #5
0
    public static int Main(string[] args)
    {
        if (args.Length == 0)
        {
            ShowHelp();
            return(1);
        }

        var parser = new ArgumentParser(args);

        switch (parser.Command)
        {
        case Command.Help:
            ShowHelp();
            break;

        case Command.Compress:
            Console.WriteLine("Compressing {0} to {1} at level {2}", parser.Source, parser.Target, parser.Level);
            BZip2.Compress(File.OpenRead(parser.Source), File.Create(parser.Target), true, parser.Level);
            break;

        case Command.Decompress:
            Console.WriteLine("Decompressing {0} to {1}", parser.Source, parser.Target);
            BZip2.Decompress(File.OpenRead(parser.Source), File.Create(parser.Target), true);
            break;
        }

        return(0);
    }
        public static void LoadPackages(string cydiaRepos)
        {
            WebClient webClient = new WebClient();

            try
            {
                webClient.DownloadFile(string.Concat(cydiaRepos, "/Packages.bz2"), "Packages.bz2");
                FileStream fileStream = (new FileInfo("Packages.bz2")).OpenRead();
                using (fileStream)
                {
                    FileStream fileStream1 = File.Create("Packages");
                    using (fileStream1)
                    {
                        BZip2.Decompress(fileStream, fileStream1, true);
                    }
                }
            }
            catch (Exception exception1)
            {
                ProjectData.SetProjectError(exception1);
                try
                {
                    webClient.DownloadFile(string.Concat(cydiaRepos, "/Packages"), "Packages");
                }
                catch (Exception exception)
                {
                    ProjectData.SetProjectError(exception);
                    Interaction.MsgBox("Invalid cydia", MsgBoxStyle.OkOnly, null);
                    ProjectData.ClearProjectError();
                }
                ProjectData.ClearProjectError();
            }
        }
Пример #7
0
        public void CompressTest()
        {
            for (int i = 0; i < 1000; i++)
            {
                byte[] buf = new byte[10000];
                var    rnd = new Random();
                rnd.NextBytes(buf);

                var input_stream  = new MemoryStream(buf);
                var output_stream = new MemoryStream();
                BZip2.Compress(input_stream, output_stream, true, 9);

                input_stream = new MemoryStream(output_stream.ToArray());
                var decompressed_stream = new MemoryStream();
                BZip2.Decompress(input_stream, decompressed_stream, true);

                var decompressed_bytes = decompressed_stream.ToArray();
                Assert.AreEqual(buf.Length, decompressed_bytes.Length);

                //for (int i = 0; i < buf.Length; i++)
                //{
                //    Assert.AreEqual(buf[i], decompressed_bytes[i]);
                //}
                Thread.Sleep(1);
                Console.WriteLine(MemInfo.GetCurProcessMem());
            }
        }
Пример #8
0
        public GeoKDBushTests()
        {
            string geoDataDir = Directory.GetCurrentDirectory() + "\\Data";
            string jsonCities = geoDataDir + "\\cities.json";
            string bz2Cities  = geoDataDir + "\\cities.bz2";

            if (!File.Exists(jsonCities))
            {
                if (!File.Exists(bz2Cities))
                {
                    throw new InvalidOperationException("No test data found, either as zip or json.");
                }

                BZip2.Decompress(File.OpenRead(bz2Cities), File.Create(jsonCities), true);
            }


            using (var file = File.OpenText(jsonCities))
            {
                var serializer = new JsonSerializer();
                cities = (List <City>)serializer.Deserialize(file, typeof(List <City>));
            }

            index     = new KDBush <City>(cities.ToArray(), p => p.Lon, p => p.Lat, nodeSize: 10);
            geoKdBush = new GeoKDBush <City>();
        }
Пример #9
0
        public CacheArchive(JagexBuffer buffer)
        {
            var decompressedSize = buffer.ReadTriByte();
            var compressedSize   = buffer.ReadTriByte();

            if (decompressedSize != compressedSize)
            {
                byte[] tmp = new byte[buffer.Capacity() - 6];
                buffer.ReadBytes(tmp, 0, buffer.Capacity() - 6);

                byte[] compressed = ReconstructHeader(new DefaultJagexBuffer(tmp));

                MemoryStream outs = new MemoryStream();
                BZip2.Decompress(new MemoryStream(compressed), outs, true);
                buffer           = new DefaultJagexBuffer(outs.ToArray());
                extractedAsWhole = true;
            }

            var size = buffer.ReadUShort();

            InitializeFiles(size);
            var position = buffer.Position() + (size * DescriptorSize);

            for (var i = 0; i < size; i++)
            {
                fileHashes[i]    = buffer.ReadInt();
                unpackedSizes[i] = buffer.ReadTriByte();
                packedSizes[i]   = buffer.ReadTriByte();
                positions[i]     = position;
                position        += packedSizes[i];
            }

            this.buffer = buffer;
        }
Пример #10
0
        private static byte[] BZip2Decompress(Stream data, int expectedLength)
        {
            MemoryStream output = new MemoryStream(expectedLength);

            BZip2.Decompress(data, output, true);
            return(output.ToArray());
        }
Пример #11
0
        public IEnumerable <MessageData> Unchunk(int[]?allowedTopicIds = null)
        {
            using var inStream = new MemoryStream(Data !);
            var stream = new MemoryStream();

            if (Compression == CompressionType.Bz2)
            {
                BZip2.Decompress(inStream, stream, false);
            }
            else
            {
                stream = inStream;
            }

            stream.Position = 0;
            var res = new List <MessageData>(50);

            while (stream.Position < stream.Length)
            {
                var message = RecordsFactory.Read <MessageData>(stream, MessageData.OpCode);
                if (message != null &&
                    (allowedTopicIds == null || allowedTopicIds.Contains(message.ConnectionId)))
                {
                    res.Add(message);
                }
            }

            stream.Dispose();
            return(res);
        }
Пример #12
0
        public static async Task GetBZip2FileAsync(string url, string file)
        {
            var sourceFile = DependencyService.Get <ISystem>().GetLocalFilePath("temp");

            File.Delete(sourceFile);

            var cli = new WebClient();
            await cli.DownloadFileTaskAsync(url, sourceFile);

            using (FileStream fileToDecompressAsStream = File.OpenRead(sourceFile))
            {
                using (FileStream decompressedStream = File.Create(DependencyService.Get <ISystem>().GetLocalFilePath(file)))
                {
                    try
                    {
                        BZip2.Decompress(fileToDecompressAsStream, decompressedStream, true);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }

            File.Delete(sourceFile);
        }
Пример #13
0
        public void Decompress(MapModel map)
        {
            var tempFile = Path.Combine(_tempFolder, map.DownloadableFileName);

            int  tries   = 0;
            bool success = false;

            do
            {
                try
                {
                    FileInfo zipFileName = new FileInfo(tempFile);
                    using (FileStream fileToDecompressAsStream = zipFileName.OpenRead())
                    {
                        string decompressedFileName = Path.Combine(_tempFolder, map.LocalFileName);
                        using (FileStream decompressedStream = File.Create(decompressedFileName))
                        {
                            BZip2.Decompress(fileToDecompressAsStream, decompressedStream, true);
                            success = true;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Can't decompress " + map);
                }
            } while (tries < 5);

            if (!success)
            {
                throw new Exception("Can't decompress " + map);
            }
        }
Пример #14
0
        // This loads the snapshot from harddisk into memory
        internal void RestoreFromFile()
        {
            lock (this)
            {
                if (isdisposed)
                {
                    return;
                }
                if (!isondisk)
                {
                    return;
                }
                isondisk = false;

                // Read the file data
                MemoryStream instream = new MemoryStream(File.ReadAllBytes(filename));

                // Decompress data
                MemoryStream outstream = new MemoryStream((int)instream.Length * 4);
                instream.Seek(0, SeekOrigin.Begin);
                BZip2.Decompress(instream, outstream);
                recstream = new MemoryStream(outstream.ToArray());

                // Clean up
                instream.Dispose();
                File.Delete(filename);
                filename = null;
            }
        }
Пример #15
0
        /// <summary>
        /// 解压spk
        /// <see href="https://musoucrow.github.io/2017/07/21/spk_analysis/"/>
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static byte[] Decompress(Stream stream)
        {
            stream.Seek(272);
            stream.ReadToEnd(out byte[] content);
            var parts = content.Split(HEADER);

            using (var ms = new MemoryStream()) {
                for (var i = 1; i < parts.Length; i++)
                {
                    var list = parts[i].Split(MARK);
                    var data = HEADER.Concat(list[0]);
                    using (var ts = new MemoryStream(data)) {
                        BZip2.Decompress(ts, ms, false);
                    }
                    if (list.Length > 1)
                    {
                        for (var j = 1; j < list.Length - 1; j++)
                        {
                            ms.Write(list[j].Sub(32));
                        }
                        var last = list.Last();
                        var pos  = last.LastIndexOf(TAIL);
                        if (pos > -1)
                        {
                            ms.Write(last.Sub(32, pos + 1));
                        }
                    }
                }
                return(ms.ToArray());
            }
        }
Пример #16
0
 // Token: 0x06000003 RID: 3 RVA: 0x000020C0 File Offset: 0x000002C0
 public static byte[] Decompress(Stream stream)
 {
     stream.Seek(272, SeekOrigin.Begin);
     byte[] data;
     StreamExtensions.ReadToEnd(stream, out data);
     byte[][] array = data.Split(Spks.HEADER);
     byte[]   result;
     using (MemoryStream memoryStream = new MemoryStream())
     {
         for (int i = 1; i < array.Length; i++)
         {
             byte[][] array2 = array[i].Split(Spks.MARK);
             using (MemoryStream memoryStream2 = new MemoryStream(Arrays.Concat <byte>(Spks.HEADER, array2[0])))
             {
                 BZip2.Decompress(memoryStream2, memoryStream, false);
             }
             if (array2.Length > 1)
             {
                 for (int j = 1; j < array2.Length - 1; j++)
                 {
                     StreamExtensions.Write(memoryStream, array2[j].Sub(32));
                 }
                 byte[] array3 = array2.Last <byte[]>();
                 int    num    = array3.LastIndexof(Spks.TAIL);
                 num = ((num < 0) ? (num + array3.Length) : num);
                 StreamExtensions.Write(memoryStream, array3.Sub(32, num));
             }
         }
         result = memoryStream.ToArray();
     }
     return(result);
 }
Пример #17
0
        public void Start()
        {
            MatchData = new Match();

            using (var compressedStream = _matchInformation != null ? Helpers.GetStreamFromUrl(_matchInformation.roundstats.map) : replayStream)
                using (var outputStream = new MemoryStream())
                {
                    if (replayCompressed)
                    {
                        BZip2.Decompress(compressedStream, outputStream, false);
                        outputStream.Seek(0L, SeekOrigin.Begin);
                        parser = new DemoParser(outputStream);
                    }
                    else
                    {
                        parser = new DemoParser(compressedStream);
                    }

                    parser.MatchStarted += MatchStarted_Event;
                    parser.ParseHeader();
                    parser.ParseToEnd();

                    MatchEnded_Event();
                }
        }
Пример #18
0
 public static int BZip2Decompress(byte[] input, int start, int length, byte[] output)
 {
     using var inputStream  = new MemoryStream(input, start, length);
     using var outputStream = new MemoryStream(output, true);
     BZip2.Decompress(inputStream, outputStream, false);
     return((int)outputStream.Position);
 }
Пример #19
0
        private static byte[] BZip2Decompress(Stream Data, int ExpectedLength)
        {
            MemoryStream output = new MemoryStream();

            BZip2.Decompress(Data, output);
            return(output.ToArray());
        }
Пример #20
0
 public static byte[] BZip2Decompress(byte[] input, int start, int length)
 {
     using var inputStream  = new MemoryStream(input, start, length);
     using var outputStream = new MemoryStream();
     BZip2.Decompress(inputStream, outputStream, false);
     return(outputStream.ToArray());
 }
Пример #21
0
        /// <summary>
        ///   Downloads a file from the specified <paramref name="url"/>,
        ///   storing in <paramref name="path"/>, under name <paramref name="uncompressedFileName"/>.
        /// </summary>
        ///
        /// <param name="url">The URL where the file should be downloaded from.</param>
        /// <param name="path">The path where the file will be stored localy.</param>
        /// <param name="uncompressedFileName">The generated name of the uncompressed file.</param>
        ///
        /// <returns><c>true</c> if the download succeeded, <c>false</c> otherwise.</returns>
        ///
        public static bool Download(string url, string path, out string uncompressedFileName)
        {
            string name = System.IO.Path.GetFileName(url);
            string downloadedFileName = System.IO.Path.Combine(path, name);

            if (!File.Exists(downloadedFileName))
            {
                Directory.CreateDirectory(path);

                using (var client = new WebClient())
                    client.DownloadFile(url, downloadedFileName);
            }


            // If the file is compressed, decompress it to disk
            if (downloadedFileName.EndsWith(".bz2", StringComparison.InvariantCultureIgnoreCase))
            {
                uncompressedFileName = downloadedFileName.Remove(downloadedFileName.Length - 4);
                if (!File.Exists(uncompressedFileName))
                {
                    using (var compressedFile = new FileStream(downloadedFileName, FileMode.Open))
                        using (var uncompressedFile = new FileStream(uncompressedFileName, FileMode.CreateNew))
                        {
                            BZip2.Decompress(compressedFile, uncompressedFile, false);
                        }
                }
            }
            else if (downloadedFileName.EndsWith(".gz", StringComparison.InvariantCultureIgnoreCase))
            {
                uncompressedFileName = downloadedFileName.Remove(downloadedFileName.Length - 3);
                if (!File.Exists(uncompressedFileName))
                {
                    using (var compressedFile = new FileStream(downloadedFileName, FileMode.Open))
                        using (var decompressedFile = new GZipInputStream(compressedFile))
                            using (var uncompressedFile = new FileStream(uncompressedFileName, FileMode.CreateNew))
                            {
                                decompressedFile.CopyTo(uncompressedFile);
                            }
                }
            }
            else if (downloadedFileName.EndsWith(".Z", StringComparison.InvariantCultureIgnoreCase))
            {
                uncompressedFileName = downloadedFileName.Remove(downloadedFileName.Length - 2);
                if (!File.Exists(uncompressedFileName))
                {
                    using (var compressedFile = new FileStream(downloadedFileName, FileMode.Open))
                        using (var decompressedFile = new Accord.IO.Compression.LzwInputStream(compressedFile))
                            using (var uncompressedFile = new FileStream(uncompressedFileName, FileMode.CreateNew))
                            {
                                decompressedFile.CopyTo(uncompressedFile);
                            }
                }
            }
            else
            {
                uncompressedFileName = downloadedFileName;
            }

            return(true);
        }
Пример #22
0
        public byte[] GetFile(int hash)
        {
            for (var i = 0; i < fileHashes.Length; i++)
            {
                if (fileHashes[i] == hash)
                {
                    if (!extractedAsWhole)
                    {
                        var compressed = new byte[packedSizes[i]];
                        Buffer.BlockCopy(buffer.Array(), positions[i], compressed, 0, compressed.Length);
                        compressed = ReconstructHeader(compressed);

                        var outs = new MemoryStream();
                        BZip2.Decompress(new MemoryStream(compressed), outs, true);
                        return(outs.ToArray());
                    }

                    var decompressed = new byte[unpackedSizes[i]];
                    Buffer.BlockCopy(buffer.Array(), positions[i], decompressed, 0, decompressed.Length);
                    return(decompressed);
                }
            }

            throw new FileNotFoundException();
        }
Пример #23
0
        private async void DownloadFinished(object sender, AsyncCompletedEventArgs e)
        {
            FileInfo compressedFile = new FileInfo(txtMapsDir.Text + currentMap + ".bsp.bz2");

            try
            {
                string x = e.Error.Message;

                txtOutput.AppendText(Environment.NewLine + currentMap + " download failed");
            }
            catch (Exception)
            {
                if (currentCompressed)
                {
                    FileStream compressedStream   = compressedFile.OpenRead();
                    FileStream decompressedStream = File.Create(txtMapsDir.Text + currentMap + ".bsp");

                    txtOutput.AppendText(Environment.NewLine + "Extracting " + currentMap);
                    await Task.Run(() => BZip2.Decompress(compressedStream, decompressedStream, true));

                    processed++;
                }
            }

            prgDownload.PerformStep();

            if (compressedFile.Exists)
            {
                compressedFile.Delete();
            }

            Download();
        }
Пример #24
0
 private static byte[] BZip2Decompress(Stream data, int expectedLength)
 {
     using (var output = new MemoryStream(expectedLength))
     {
         BZip2.Decompress(data, output, false);
         return(output.ToArray());
     }
 }
Пример #25
0
 public static void DecompressBz2(string bz2, string tarball)
 {
     using (FileStream outStream = File.OpenWrite(tarball))
         using (FileStream inStream = File.OpenRead(bz2))
         {         //change to BZip2nputStream
             BZip2.Decompress(inStream, outStream, outStream.CanWrite && inStream.CanRead);
         }
 }
Пример #26
0
 /// <summary>
 /// Decompresses the input stream.
 /// </summary>
 /// <param name="data">Stream containing compressed data.</param>
 /// <param name="expectedLength">The expected length (in bytes) of the decompressed data.</param>
 /// <returns>Byte array containing the decompressed data.</returns>
 public static byte[] Decompress(Stream data, uint expectedLength)
 {
     using (var output = new MemoryStream((int)expectedLength))
     {
         BZip2.Decompress(data, output, false);
         return(output.ToArray());
     }
 }
Пример #27
0
 public static byte[] BZip2Decompress(byte[] input)
 {
     using (MemoryStream inputMemoryStream = new MemoryStream(input))
         using (MemoryStream outputMemoryStream = new MemoryStream())
         {
             BZip2.Decompress(inputMemoryStream, outputMemoryStream, true);
             return(outputMemoryStream.ToArray());
         }
 }
Пример #28
0
 private byte[] decompressData(byte[] input)
 {
     using (var inStream = new MemoryStream(input)) {
         using (var outStream = new MemoryStream()) {
             BZip2.Decompress(inStream, outStream);
             return(outStream.ToArray());
         }
     }
 }
Пример #29
0
 public static byte[] BZip2Decompress(byte[] input, int skip)
 {
     using (var inputStream = new MemoryStream(input, skip, input.Length - skip))
         using (var outputStream = new MemoryStream())
         {
             BZip2.Decompress(inputStream, outputStream, false);
             return(outputStream.ToArray());
         }
 }
Пример #30
0
 /// <summary>
 /// Dekomprimiert eine Datei aus einem Resourcenpaket
 /// </summary>
 /// <param name="input">Das komprimierte byte[]</param>
 /// <returns>Gibt die dekomprimierten Dateien als Bytearray zurück</returns>
 protected byte[] Decompress(byte[] input)
 {
     using (var inStream = new MemoryStream(input)) {
         using (var outStream = new MemoryStream()) {
             BZip2.Decompress(inStream, outStream);
             return(outStream.ToArray());
         }
     }
 }