コード例 #1
1
ファイル: Lzma.cs プロジェクト: IsaacSanch/KoruptLib
        public static void ExtractWrappedArchive(string filePath, string targetPath)
        {
            Inits.EnsureBinaries();
            FileInfo ufil = new FileInfo(filePath);

            if (!ufil.Exists)
                throw new FileNotFoundException();

            using (FileStream fs = ufil.OpenRead()) {
                using (MemoryStream ms = new MemoryStream()) {
                    using (LzmaDecodeStream dec = new LzmaDecodeStream(fs)) {
                        int byt = 0;
                        while ((byt = dec.ReadByte()) != -1) {
                            ms.WriteByte((byte)byt);
                        }
                    }

                    using (SevenZipExtractor ex = new SevenZipExtractor(ms)) {
                        ex.ExtractFiles(
                            f => {
                                string file = string.Format("{0}{1}{2}",
                                    targetPath.TrimEnd(Path.DirectorySeparatorChar),
                                    Path.DirectorySeparatorChar,
                                    f.ArchiveFileInfo.FileName
                                );
                                string dir = Path.GetDirectoryName(file);
                                if (!Directory.Exists(dir))
                                    Directory.CreateDirectory(dir);
                                f.ExtractToFile = file;
                            }
                        );
                    }
                }
            }
        }
コード例 #2
0
        private void Decompress(string[] args)
        {
            //If no file name is specified, write usage text.

            if (args.Length == 0)
            {
                Console.WriteLine("error");
            }
            else
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (File.Exists(args[i]))
                    {
                        SevenZipExtractor.SetLibraryPath(@"C:\Users\thlacroi\AppData\Local\Apps\COMOS\COMOS Walkinside 6.2 (64 bit)\7z.dll");
                        using (var tmp = new SevenZipExtractor(args[i]))
                        {
                            for (int n = 0; n < tmp.ArchiveFileData.Count; n++)
                            {
                                if (tmp.ArchiveFileData[n].FileName.Contains(".xml"))
                                {
                                    tmp.ExtractFiles(Path.Combine(Resource.DirectoryTmp, i.ToString()), tmp.ArchiveFileData[n].Index);
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #3
0
ファイル: Compression.cs プロジェクト: MaHuJa/withSIX.Desktop
 static void UnpackArchive(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder, bool overwrite,
     bool checkFileIntegrity,
     SevenZipExtractor extracter) {
     if (checkFileIntegrity && !extracter.Check())
         throw new Exception(String.Format("Appears to be an invalid archive: {0}", sourceFile));
     outputFolder.MakeSurePathExists();
     extracter.ExtractFiles(outputFolder.ToString(), overwrite
         ? extracter.ArchiveFileNames.ToArray()
         : extracter.ArchiveFileNames.Where(x => !outputFolder.GetChildFileWithName(x).Exists)
             .ToArray());
 }
コード例 #4
0
 public ActionResult Create(Video video, HttpPostedFileBase previewZip)
 {
     if (!ModelState.IsValid || previewZip == null || !(previewZip.ContentLength > 0))
     {
         return View();
     }
     else
     {
         using (var tmp = new SevenZipExtractor(previewZip.InputStream))
         {
             for (int i = 0; i < tmp.ArchiveFileData.Count; i++)
             {
                 var fileData = tmp.ArchiveFileData[i];
                 if (fileData.FileName.EndsWith("png") || fileData.FileName.EndsWith("jpg"))
                 {
                     tmp.ExtractFiles(Server.MapPath("~/Content/Images/"), fileData.Index);
                 }
                 else if (fileData.FileName.EndsWith("mp4") || fileData.FileName.EndsWith("webm"))
                 {
                     tmp.ExtractFiles(Server.MapPath("~/Content/VideoPreviews/"), fileData.Index);
                 }
                 else
                 {
                     ModelState.AddModelError("", new Exception("Wrong file format"));
                     return View();
                 }
             }
         }
         _videoRepository.Add(video);
         //var fileName = video.Title;
         //var path = Path.Combine(Server.MapPath("~/Content/Images/"), fileName + Path.GetExtension(previewZip.FileName));
         //previewZip.SaveAs(path);
         _cacheManager.Add(video);
         return RedirectToAction("Index");
     }
 }
コード例 #5
0
ファイル: LegendsViewer.cs プロジェクト: RossM/Legends-Viewer
        private void extractZip_DoWork(object sender, DoWorkEventArgs e)
        {
            using (SevenZipExtractor extractor = new SevenZipExtractor(e.Argument as String))
            {
                if (extractor.ArchiveFileNames.Count(file => file.EndsWith(".xml")) > 1 || extractor.ArchiveFileNames.Count(file => file.EndsWith(".xml")) == 0)
                    throw new Exception("Not enough or too many XML Files");
                if (extractor.ArchiveFileNames.Count(file => file.EndsWith(".world_history.txt")) > 1 || extractor.ArchiveFileNames.Count(file => file.EndsWith("-world_history.txt")) == 0)
                    throw new Exception("Not enough or too many World History Text Files");
                if (extractor.ArchiveFileNames.Count(file => file.EndsWith("-world_sites_and_pops.txt")) > 1 || extractor.ArchiveFileNames.Count(file => file.EndsWith("-world_sites_and_pops.txt")) == 0)
                    throw new Exception("Not enough or too many Site & Pops Text Files");
                if (extractor.ArchiveFileNames.Count(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")) == 0)
                    throw new Exception("No map image found.");

                string xml = extractor.ArchiveFileNames.Where(file => file.EndsWith(".xml")).Single();
                if (File.Exists(xml)) throw new Exception(xml + " already exists.");
                extractor.ExtractFiles(System.IO.Directory.GetCurrentDirectory(), xml);
                extractedFiles.Add(xml);

                string history = extractor.ArchiveFileNames.Where(file => file.EndsWith("-world_history.txt")).Single();
                if (File.Exists(history)) throw new Exception(history + " already exists.");
                extractor.ExtractFiles(System.IO.Directory.GetCurrentDirectory(), history);
                extractedFiles.Add(history);

                string sites = extractor.ArchiveFileNames.Where(file => file.EndsWith("-world_sites_and_pops.txt")).Single();
                if (File.Exists(sites)) throw new Exception(sites + " already exists.");
                extractor.ExtractFiles(System.IO.Directory.GetCurrentDirectory(), sites);
                extractedFiles.Add(sites);

                string map = "";

                if (extractor.ArchiveFileNames.Count(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")) == 1)
                    map = extractor.ArchiveFileNames.Single(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg"));
                else
                {
                    dlgFileSelect fileSelect = new dlgFileSelect(extractor.ArchiveFileNames.Where(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")).ToList());
                    fileSelect.Text = "Select Base Map";
                    fileSelect.ShowDialog();
                    if (fileSelect.SelectedFile == "") throw new Exception("No map file selected.");
                    if (File.Exists(fileSelect.SelectedFile)) { MessageBox.Show(fileSelect.SelectedFile + " already exists."); return; }
                    map = fileSelect.SelectedFile;
                }

                //extractor.ArchiveFileNames.Where(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")).Single();
                if (File.Exists(map)) throw new Exception(map + " already exists.");
                extractor.ExtractFiles(Directory.GetCurrentDirectory(), map);
                extractedFiles.Add(map);
            }
        }
コード例 #6
0
		public void ExtractionTestExtractFiles(string format){
			using (var tmp = new SevenZipExtractor(Path.Combine(archivePath, "Test."+format)))
				for (int i = 0; i < tmp.ArchiveFileData.Count; i++) tmp.ExtractFiles(tempFolder, tmp.ArchiveFileData[i].Index);
		}
コード例 #7
0
        /// <summary>
        /// Downloads update and installs the update
        /// </summary>
        /// <param name="update">The update xml info</param>
        private void DownloadUpdate(SharpUpdateXml update)
        {
            SharpUpdateDownloadForm form = new SharpUpdateDownloadForm(update.Uri, update.MD5, this.applicationInfo.ApplicationIcon);
            DialogResult result = form.ShowDialog(this.applicationInfo.Context);

            // Download update
            if (result == DialogResult.OK)
            {
                using (var tmp = new SevenZipExtractor(form.TempFilePath))
                {
                    for (int i = 0; i < tmp.ArchiveFileData.Count; i++)
                    {
                        tmp.ExtractFiles(@"d:\Temp\Result\", tmp.ArchiveFileData[i].Index);
                    }
                }

                string currentPath = this.applicationInfo.ApplicationAssembly.Location;
                string newPath = Path.GetDirectoryName(currentPath) + "\\" + update.FileName;

                // "Install" it
                UpdateApplication(form.TempFilePath, currentPath, newPath, update.LaunchArgs);

                Application.Exit();
            }
            else if (result == DialogResult.Abort)
            {
                MessageBox.Show("The update download was cancelled.\nThis program has not been modified.", "Update Download Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("There was a problem downloading the update.\nPlease try again later.", "Update Download Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
コード例 #8
0
        static void Main(string[] args)
        {          
            Console.WriteLine("SevenZipSharp test application.");
            //Console.ReadKey();

            /*
             You may specify the custom path to 7-zip dll at SevenZipLibraryManager.LibraryFileName 
                or call SevenZipExtractor.SetLibraryPath(@"c:\Program Files\7-Zip\7z.dll");
                or call SevenZipCompressor.SetLibraryPath(@"c:\Program Files\7-Zip\7z.dll");
             You may check if your library fits your goals with
                (SevenZipExtractor/Compressor.CurrentLibraryFeatures & LibraryFeature.<name>) != 0
             Internal benchmark:
                var features = SevenZip.SevenZipExtractor.CurrentLibraryFeatures;
                Console.WriteLine(((uint)features).ToString("X6"));
            */

            string SevenZipPath = @"C:\Program Files\7-Zip\7z.dll";

            SevenZipExtractor.SetLibraryPath(SevenZipPath);
            SevenZipCompressor.SetLibraryPath(SevenZipPath);

            #region Temporary test
            var features = SevenZipExtractor.CurrentLibraryFeatures;
            Console.WriteLine(((uint)features).ToString("X6"));
            #endregion

            #region Extraction test - ExtractFiles
            using (var tmp = new SevenZipExtractor(@"d:\Temp\tweetservice.7z"))
            {
                tmp.FileExtractionStarted += (s, e) =>
                {
                    Console.WriteLine(String.Format("[{0}%] {1}",
                        e.PercentDone, e.FileInfo.FileName));
                };

                for (int i = 0; i < tmp.ArchiveFileData.Count; i++)
                {
                    tmp.ExtractFiles(@"d:\Temp\Result\", tmp.ArchiveFileData[i].Index);
                }
                // To extract more than 1 file at a time or when you definitely know which files to extract,
                // use something like
                //tmp.ExtractFiles(@"d:\Temp\Result", 1, 3, 5);
            }
            //
            #endregion

            #region Extraction test - multivolumes
            //SevenZipExtractor.SetLibraryPath(@"d:\Work\Misc\7zip\9.04\CPP\7zip\Bundles\Format7zF\7z.dll");
            /*using (var tmp = new SevenZipExtractor(@"d:\Temp\The_Name_of_the_Wind.part1.rar"))
            {                
                tmp.ExtractArchive(@"d:\Temp\!Пусто");
            }
            //*/
            #endregion

            #region Compression tests - very simple
            var tmpComp = new SevenZipCompressor();
            tmpComp.VolumeSize = 10*1024*1024; // 10 MegaByte per Volume MultiPart Test

            tmpComp.FileCompressionStarted += (s, e) =>
                    Console.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName));

            //tmp.ScanOnlyWritable = true;
            //tmp.CompressFiles(@"d:\Temp\arch.7z", @"d:\Temp\log.txt");
            //tmp.CompressDirectory(@"c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\1033", @"D:\Temp\arch.7z");
            tmpComp.CompressDirectory(@"D:\Temp\CompressTest", @"d:\Temp\test.7z");
            //
            #endregion
            
            #region Compression test - features Append mode
            /*var tmp = new SevenZipCompressor();
            tmp.CompressionMode = CompressionMode.Append;            
            tmp.CompressDirectory(@"D:\Temp\!Пусто", @"D:\Temp\arch.7z");
            tmp = null;
            //*/
            #endregion

            #region Compression test - features Modify mode
            /*var tmp = new SevenZipCompressor();
            tmp.ModifyArchive(@"d:\Temp\7z465_extra.7z", new Dictionary<int, string>() { { 0, "xxx.bat" } });
            //Delete
            //tmp.ModifyArchive(@"d:\Temp\7z465_extra.7z", new Dictionary<int, string>() { { 19, null }, { 1, null } });
            //*/
            #endregion

            #region Compression test - multivolumes
            /*var tmp = new SevenZipCompressor();
            tmp.VolumeSize = 10000;            
            tmp.CompressDirectory(@"D:\Temp\!Пусто", @"D:\Temp\arch.7z");            
            //*/
            #endregion
            
            #region Extraction test. Shows cancel feature.
            /*using (var tmp = new SevenZipExtractor(@"D:\Temp\test.7z"))
            {
                tmp.FileExtractionStarted += (s, e) =>
                {
                    /*if (e.FileInfo.Index == 10)
                    {
                        e.Cancel = true;
                        Console.WriteLine("Cancelled");
                    }
                    else
                    {//*//*
                        
                       Console.WriteLine(String.Format("[{0}%] {1}",
                           e.PercentDone, e.FileInfo.FileName));
                   //}
               };
               tmp.FileExists += (o, e) =>
               {
                   Console.WriteLine("Warning: file \"" + e.FileName + "\" already exists.");
                   //e.Overwrite = false;
               };
               tmp.ExtractionFinished += (s, e) => { Console.WriteLine("Finished!"); };
               tmp.ExtractArchive(@"D:\Temp\!Пусто");
            }
            //*/
            #endregion

            #region Compression test - shows lots of features 
            /*var tmp = new SevenZipCompressor();
            tmp.ArchiveFormat = OutArchiveFormat.SevenZip;
            tmp.CompressionLevel = CompressionLevel.High;
            tmp.CompressionMethod = CompressionMethod.Ppmd;
            tmp.FileCompressionStarted += (s, e) =>
            {
                /*if (e.PercentDone > 50)
                {
                    e.Cancel = true;
                }
                else
                {
                //*//*
                    Console.WriteLine(String.Format("[{0}%] {1}",
                        e.PercentDone, e.FileName));
                //*//*}
            };
            /*
            tmp.FilesFound += (se, ea) => 
            { 
                Console.WriteLine("Number of files: " + ea.Value.ToString()); 
            };
            //*/
            /*
            tmp.CompressFiles(
                @"d:\Temp\test.bz2", @"c:\log.txt", @"d:\Temp\08022009.jpg");*/
            //tmp.CompressDirectory(@"d:\Temp\!Пусто", @"d:\Temp\arch.7z");
            #endregion

            #region Multi-threaded extraction test
            /*var t1 = new Thread(() =>
            {
                using (var tmp = new SevenZipExtractor(@"D:\Temp\7z465_extra.7z"))
                {
                    tmp.FileExtractionStarted += (s, e) =>
                    {
                        Console.WriteLine(String.Format("[{0}%] {1}",
                            e.PercentDone, e.FileInfo.FileName));
                    };
                    tmp.ExtractionFinished += (s, e) => { Console.WriteLine("Finished!"); };
                    tmp.ExtractArchive(@"D:\Temp\t1");
                }
            });
            var t2 = new Thread(() =>
            {
                using (var tmp = new SevenZipExtractor(@"D:\Temp\7z465_extra.7z"))
                {
                    tmp.FileExtractionStarted += (s, e) =>
                    {
                        Console.WriteLine(String.Format("[{0}%] {1}",
                            e.PercentDone, e.FileInfo.FileName));
                    };
                    tmp.ExtractionFinished += (s, e) => { Console.WriteLine("Finished!"); };
                    tmp.ExtractArchive(@"D:\Temp\t2");
                }
            });
            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
             //*/
            #endregion

            #region Multi-threaded compression test
            /*var t1 = new Thread(() =>
            {
                var tmp = new SevenZipCompressor();
                tmp.FileCompressionStarted += (s, e) =>
                    Console.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName));
                tmp.CompressDirectory(@"D:\Temp\t1", @"D:\Temp\arch1.7z");
            });
            var t2 = new Thread(() =>
            {
                var tmp = new SevenZipCompressor();
                tmp.FileCompressionStarted += (s, e) =>
                    Console.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileName));
                tmp.CompressDirectory(@"D:\Temp\t2", @"D:\Temp\arch2.7z");
            });           
            t1.Start();
            t2.Start();           
            t1.Join();
            t2.Join();
            //*/
            #endregion

            #region Streaming extraction test
            /*using (var tmp = new SevenZipExtractor(
                File.OpenRead(@"D:\Temp\7z465_extra.7z")))
            {
                tmp.FileExtractionStarted += (s, e) =>
                {
                    Console.WriteLine(String.Format("[{0}%] {1}",
                        e.PercentDone, e.FileInfo.FileName));
                };
                tmp.ExtractionFinished += (s, e) => { Console.WriteLine("Finished!"); };
                tmp.ExtractArchive(@"D:\Temp\!Пусто");
            }//*/
            #endregion

            #region Streaming compression test
            /*var tmp = new SevenZipCompressor();
            tmp.FileCompressionStarted += (s, e) =>
            {
                Console.WriteLine(String.Format("[{0}%] {1}",
                    e.PercentDone, e.FileName));
            };
            tmp.CompressDirectory(@"D:\Temp\1",
                File.Create(@"D:\Temp\arch.bz2"));
            //*/
            #endregion

            #region CompressStream (managed) test
            /*SevenZipCompressor.CompressStream(File.OpenRead(@"D:\Temp\test.txt"), 
                File.Create(@"D:\Temp\test.lzma"), null, (o, e) =>
            {
                if (e.PercentDelta > 0)
                {
                    Console.Clear();
                    Console.WriteLine(e.PercentDone.ToString() + "%");
                }
            });
            //*/
            #endregion

            #region ExtractFile(Stream) test
            /*using (var tmp = new SevenZipExtractor(@"D:\Temp\7z465_extra.7z"))
            {
                tmp.FileExtractionStarted += (s, e) =>
                {
                    Console.WriteLine(String.Format("[{0}%] {1}",
                        e.PercentDone, e.FileInfo.FileName));
                };
                tmp.FileExists += (o, e) =>
                {
                    Console.WriteLine("Warning: file \"" + e.FileName + "\" already exists.");
                    //e.Overwrite = false;
                };
                tmp.ExtractionFinished += n(s, e) => { Console.WriteLine("Finished!"); };
                tmp.ExtractFile(2, File.Create(@"D:\Temp\!Пусто\test.txt"));
            }//*/
            #endregion

            #region ExtractFile(Disk) test
            /*using (var tmp = new SevenZipExtractor(@"D:\Temp\7z465_extra.7z"))
            {
                tmp.FileExtractionStarted += (s, e) =>
                {
                    Console.WriteLine(String.Format("[{0}%] {1}",
                        e.PercentDone, e.FileInfo.FileName));
                };
                tmp.FileExists += (o, e) =>
                {
                    Console.WriteLine("Warning: file \"" + e.FileName + "\" already exists.");
                    //e.Overwrite = false;
                };
                tmp.ExtractionFinished += (s, e) => { Console.WriteLine("Finished!"); };
                tmp.ExtractFile(4, @"D:\Temp\!Пусто");
            }
            //*/
            #endregion            

            #region CompressFiles Zip test
            /*var tmp = new SevenZipCompressor();
            tmp.ArchiveFormat = OutArchiveFormat.Zip;
            tmp.CompressFiles(@"d:\Temp\arch.zip", @"d:\Temp\gpl.txt", @"d:\Temp\ru_office.txt");
            //*/
            #endregion

            #region CompressStream (external) test
            /*var tmp = new SevenZipCompressor();
            tmp.CompressStream(
                File.OpenRead(@"D:\Temp\08022009.jpg"),
                File.Create(@"D:\Temp\arch.7z"));
            //*/
            #endregion

            #region CompressFileDictionary test
            /*var tmp = new SevenZipCompressor();
            Dictionary<string, string> fileDict = new Dictionary<string, string>();
            fileDict.Add("test.ini", @"d:\Temp\temp.ini");
            tmp.FileCompressionStarted += (o, e) =>
            {               
                Console.WriteLine(String.Format("[{0}%] {1}",
                        e.PercentDone, e.FileName));
            };
            tmp.CompressFileDictionary(fileDict, @"d:\Temp\arch.7z");
            //*/
            #endregion

            #region Toughness test - throws no exceptions and no leaks
            /*
            Console.ReadKey();
            string exeAssembly = Assembly.GetAssembly(typeof(SevenZipExtractor)).FullName;
            AppDomain dom = AppDomain.CreateDomain("Extract");
            for (int i = 0; i < 1000; i++)
            {
                using (SevenZipExtractor tmp = 
                    (SevenZipExtractor)dom.CreateInstance(
                    exeAssembly, typeof(SevenZipExtractor).FullName,
                    false, BindingFlags.CreateInstance, null, 
                    new object[] {@"D:\Temp\7z465_extra.7z"}, 
                    System.Globalization.CultureInfo.CurrentCulture, null, null).Unwrap())
                {                    
                    tmp.ExtractArchive(@"D:\Temp\!Пусто");
                }
                Console.Clear();
                Console.WriteLine(i);
            }
            AppDomain.Unload(dom);           
            //No errors, no leaks*/
            #endregion

            #region Serialization demo
            /*ArgumentException ex = new ArgumentException("blahblah");
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                bf.Serialize(ms, ex);
                SevenZipCompressor cmpr = new SevenZipCompressor();
                cmpr.CompressStream(ms, File.Create(@"d:\Temp\test.7z"));
            }
            //*/
            #endregion

            #region Compress with custom parameters demo
            /*var tmp = new SevenZipCompressor();            
            tmp.ArchiveFormat = OutArchiveFormat.Zip;
            tmp.CompressionMethod = CompressionMethod.Deflate;
            tmp.CompressionLevel = CompressionLevel.Ultra;
            //Number of fast bytes
            tmp.CustomParameters.Add("fb", "256");
            //Number of deflate passes
            tmp.CustomParameters.Add("pass", "4");
            //Multi-threading on
            tmp.CustomParameters.Add("mt", "on");
            tmp.ZipEncryptionMethod = ZipEncryptionMethod.AES256;
            tmp.Compressing += (s, e) =>
            {
                Console.Clear();
                Console.WriteLine(String.Format("{0}%", e.PercentDone));
            };
            tmp.CompressDirectory(@"d:\Temp\!Пусто", @"d:\Temp\arch.zip", "test");
            //*/

            /*SevenZipCompressor tmp = new SevenZipCompressor();
            tmp.CompressionMethod = CompressionMethod.Ppmd;
            tmp.CompressionLevel = CompressionLevel.Ultra;
            tmp.EncryptHeadersSevenZip = true;
            tmp.ScanOnlyWritable = true;
            tmp.CompressDirectory(@"d:\Temp\!Пусто", @"d:\Temp\arch.7z", "test");  
            //*/
            #endregion

            #region Sfx demo
            /*var sfx = new SevenZipSfx();
            SevenZipCompressor tmp = new SevenZipCompressor();
            using (MemoryStream ms = new MemoryStream())
            {
                tmp.CompressDirectory(@"d:\Temp\!Пусто", ms);               
                sfx.MakeSfx(ms, @"d:\Temp\test.exe");
            }
            //*/
            #endregion

            #region Lzma Encode/Decode Stream test
            /*using (var output = new FileStream(@"d:\Temp\arch.lzma", FileMode.Create))
            {
                var encoder = new LzmaEncodeStream(output);
                using (var inputSample = new FileStream(@"d:\Temp\tolstoi_lev_voina_i_mir_kniga_1.rtf", FileMode.Open))
                {
                    int bufSize = 24576, count;
                    byte[] buf = new byte[bufSize];
                    while ((count = inputSample.Read(buf, 0, bufSize)) > 0)
                    {
                        encoder.Write(buf, 0, count);
                    }
                }
                encoder.Close();
            }//*/
            /*using (var input = new FileStream(@"d:\Temp\arch.lzma", FileMode.Open))
            {
                var decoder = new LzmaDecodeStream(input);
                using (var output = new FileStream(@"d:\Temp\res.rtf", FileMode.Create))
                {
                    int bufSize = 24576, count;
                    byte[] buf = new byte[bufSize];
                    while ((count = decoder.Read(buf, 0, bufSize)) > 0)
                    {
                        output.Write(buf, 0, count);
                    }
                }
            }//*/
            #endregion

            Console.WriteLine("Press any key to finish.");
            Console.ReadKey();
        }
コード例 #9
0
ファイル: MainForm.cs プロジェクト: afonsof/nes-hd
        public void OpenRom(string romPath)
        {
            _romFileName = romPath;
            if (File.Exists(romPath))
            {
                #region Check if archive

                var extension = Path.GetExtension(romPath);
                if (extension != null && extension.ToLower() != ".nes")
                {
                    try
                    {
                        _extractor = new SevenZipExtractor(romPath);
                    }
                    catch
                    {
                    }
                    if (_extractor.ArchiveFileData.Count == 1)
                    {
                        if (
                            _extractor.ArchiveFileData[0].FileName.Substring(
                                _extractor.ArchiveFileData[0].FileName.Length - 4, 4).ToLower() == ".nes")
                        {
                            _extractor.ExtractArchive(Path.GetTempPath());
                            romPath = Path.GetTempPath() + _extractor.ArchiveFileData[0].FileName;
                        }
                    }
                    else
                    {
                        var ar = new ArchivesForm(_extractor.ArchiveFileData.Select(file => file.FileName).ToArray());
                        ar.ShowDialog(this);
                        if (ar.Ok)
                        {
                            string[] fil = { ar.SelectedRom };
                            _extractor.ExtractFiles(Path.GetTempPath(), fil);
                            romPath = Path.GetTempPath() + ar.SelectedRom;
                        }
                        else
                        {
                            return;
                        }
                    }
                }

                #endregion

                #region Check the rom

                var header = new NesHeaderReader(romPath);
                if (header.ValidRom)
                {
                    if (!header.SupportedMapper())
                    {
                        MessageBox.Show("Can't load rom:\n" + romPath +
                                        "\n\nUNSUPPORTED MAPPER # " +
                                        header.MemoryMapper);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("Can't load rom:\n" + romPath +
                                    "\n\nRom is damaged or not an INES format file");
                    return;
                }

                #endregion

                //Exit current thread
                if (_engine != null)
                {
                    _engine.ShutDown();
                    _engine = null;
                }
                if (_gameThread != null)
                {
                    _gameThread.Abort();
                }
                //Start new nes !!
                if (Program.Settings.PaletteFormat == null)
                    Program.Settings.PaletteFormat = new PaletteFormat();
                _engine = new NesEngine(Program.Settings.TV, Program.Settings.PaletteFormat);
                _engine.PauseToggle += NesPauseToggle;
                if (_engine.LoadRom(romPath))
                {
                    #region Setup input

                    var manager = new InputManager(Handle);
                    var joy1 = new Joypad(manager);
                    joy1.A.Input = Program.Settings.CurrentControlProfile.Player1A;
                    joy1.B.Input = Program.Settings.CurrentControlProfile.Player1B;
                    joy1.Up.Input = Program.Settings.CurrentControlProfile.Player1Up;
                    joy1.Down.Input = Program.Settings.CurrentControlProfile.Player1Down;
                    joy1.Left.Input = Program.Settings.CurrentControlProfile.Player1Left;
                    joy1.Right.Input = Program.Settings.CurrentControlProfile.Player1Right;
                    joy1.Select.Input = Program.Settings.CurrentControlProfile.Player1Select;
                    joy1.Start.Input = Program.Settings.CurrentControlProfile.Player1Start;
                    var joy2 = new Joypad(manager);
                    joy2.A.Input = Program.Settings.CurrentControlProfile.Player2A;
                    joy2.B.Input = Program.Settings.CurrentControlProfile.Player2B;
                    joy2.Up.Input = Program.Settings.CurrentControlProfile.Player2Up;
                    joy2.Down.Input = Program.Settings.CurrentControlProfile.Player2Down;
                    joy2.Left.Input = Program.Settings.CurrentControlProfile.Player2Left;
                    joy2.Right.Input = Program.Settings.CurrentControlProfile.Player2Right;
                    joy2.Select.Input = Program.Settings.CurrentControlProfile.Player2Select;
                    joy2.Start.Input = Program.Settings.CurrentControlProfile.Player2Start;
                    _engine.SetupInput(manager, joy1, joy2);

                    #endregion

                    #region Output

                    //Set the size
                    switch (Program.Settings.Size.ToLower())
                    {
                        case "x1":
                            Size = new Size(265, 305);
                            FormBorderStyle = FormBorderStyle.FixedDialog;
                            statusStrip1.SizingGrip = false;
                            break;
                        case "x2":
                            Size = new Size(521, 529);
                            FormBorderStyle = FormBorderStyle.FixedDialog;
                            statusStrip1.SizingGrip = false;
                            break;
                        case "stretch":
                            FormBorderStyle = FormBorderStyle.Sizable;
                            statusStrip1.SizingGrip = true;
                            break;
                    }
                    //The output devices
                    var mon = new SoundDeviceGeneral16(statusStrip1) { Stereo = Program.Settings.Stereo };
                    switch (Program.Settings.GFXDevice)
                    {
                        case GraphicDevices.Gdi:
                            var gdi = new VideoGdi(Program.Settings.TV, panel1);
                            _engine.SetupOutput(gdi, mon);
                            break;
                        case GraphicDevices.GdiHiRes:
                            var gdih = new VideoGdiHiRes(Program.Settings.TV, panel1,
                                                         _engine.Memory.Map.Cartridge.RomPath,
                                                         _engine.Memory.Map.Cartridge.ChrPages);
                            _engine.SetupOutput(gdih, mon);
                            break;
                        case GraphicDevices.SlimDx:
                            var sl = new VideoSlimDx(Program.Settings.TV, panel1, _engine.Memory.Map.Cartridge.Multi);
                            _engine.SetupOutput(sl, mon);
                            break;
                        default:
                            Program.Settings.GFXDevice = GraphicDevices.SlimDx;
                            var sl1 = new VideoSlimDx(Program.Settings.TV, panel1, _engine.Memory.Map.Cartridge.Multi);
                            _engine.SetupOutput(sl1, mon);
                            break;
                    }
                    if (_engine.Ppu.OutputDevice.SupportFullScreen)
                        _engine.Ppu.OutputDevice.FullScreen = Program.Settings.Fullscreen;
                    //Audio
                    _engine.SoundEnabled = Program.Settings.SoundEnabled;
                    _engine.Apu.Square1Enabled = Program.Settings.Square1;
                    _engine.Apu.Square2Enabled = Program.Settings.Square2;
                    _engine.Apu.DMCEnabled = Program.Settings.DMC;
                    _engine.Apu.TriangleEnabled = Program.Settings.Triangle;
                    _engine.Apu.NoiseEnabled = Program.Settings.Noize;
                    _engine.Apu.VRC6P1Enabled = Program.Settings.VRC6Pulse1;
                    _engine.Apu.VRC6P2Enabled = Program.Settings.VRC6Pulse2;
                    _engine.Apu.VRC6SawToothEnabled = Program.Settings.VRC6Sawtooth;
                    _engine.Apu.SetVolume(Program.Settings.Volume);

                    #endregion

                    #region Misc

                    _engine.Ppu.NoLimiter = Program.Settings.NoLimiter;
                    _engine.AutoSaveSram = Program.Settings.AutoSaveSRAM;

                    #endregion

                    //Launch
                    _myThreadCreator = _engine.Run;
                    _gameThread = new Thread(_myThreadCreator);
                    _gameThread.Start();
                    timer_FPS.Start();
                    StatusLabel4_status.BackColor = Color.Green;
                    StatusLabel4_status.Text = "ON";
                    //Add to the recent
                    AddRecent(romPath);
                    RefreshRecents();
                    //Set the name
                    Text = "My Nes - " + Path.GetFileNameWithoutExtension(romPath);
                }
                else
                {
                    MessageBox.Show("Can't load rom:\n" + romPath +
                                    "\n\nRom is damaged or not an INES format file !!");
                    if (_engine != null)
                    {
                        _engine.ShutDown();
                        _engine = null;
                    }
                    if (_gameThread != null)
                    {
                        _gameThread.Abort();
                    }
                    return;
                }
            }
        }