Example #1
0
        private void ExtractIso(string isoPath, string destDir)
        {
            using (FileStream isoStream = File.Open(isoPath, FileMode.Open))
            {
                CDReader cd    = new CDReader(isoStream, true);
                var      files = cd.GetFiles("\\", "*.*", SearchOption.AllDirectories);

                foreach (var file in files)
                {
                    using (var stream = cd.OpenFile(file, FileMode.Open))
                    {
                        var destFile = destDir.TrimEnd('\\') + "\\" + Regex.Replace(file.Replace("/", "\\"), @";\d*$", "").TrimStart('\\');

                        // Create directories
                        var destFolder = Path.GetDirectoryName(destFile);
                        destFolder = destFolder.Equals(destDir) ? string.Empty : destFolder;

                        var finalDestFolder = destDir;
                        if (!string.IsNullOrEmpty(destFolder))
                        {
                            finalDestFolder = Path.Combine(destDir, destFolder);
                        }

                        if (!Directory.Exists(finalDestFolder))
                        {
                            Directory.CreateDirectory(finalDestFolder);
                        }

                        // Create the file
                        using (FileStream sw = new FileStream(destFile, FileMode.CreateNew))
                        {
                            byte[] buffer = new byte[2048];
                            int    bytesRead;
                            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                sw.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                }
            }
        }
 public static void CopyFilesfromISO(string isoName, string baseDirectory)
 {
     using (FileStream isoStream = File.OpenRead(isoName))
     {
         if (UdfReader.Detect(isoStream))
         {
             using (UdfReader iso = new UdfReader(isoStream))
             {
                 DoCopyFilesfromISO(iso, baseDirectory);
             }
         }
         else if (CDReader.Detect(isoStream))
         {
             using (CDReader iso = new CDReader(isoStream, true))
             {
                 DoCopyFilesfromISO(iso, baseDirectory);
             }
         }
     }
 }
        public void GetFiles()
        {
            CDBuilder builder = new CDBuilder();

            builder.AddDirectory(@"SOMEDIR\CHILD\GCHILD");
            builder.AddDirectory(@"AAA.DIR");
            builder.AddFile(@"FOO.TXT", new byte[10]);
            builder.AddFile(@"SOMEDIR\CHILD.TXT", new byte[10]);
            builder.AddFile(@"SOMEDIR\FOO.TXT", new byte[10]);
            builder.AddFile(@"SOMEDIR\CHILD\GCHILD\BAR.TXT", new byte[10]);
            CDReader fs = new CDReader(builder.Build(), false);

            Assert.Equal(1, fs.Root.GetFiles().Length);
            Assert.Equal("FOO.TXT", fs.Root.GetFiles()[0].FullName);

            Assert.Equal(2, fs.Root.GetDirectories("SOMEDIR")[0].GetFiles("*.TXT").Length);
            Assert.Equal(4, fs.Root.GetFiles("*.TXT", SearchOption.AllDirectories).Length);

            Assert.Equal(0, fs.Root.GetFiles("*.DIR", SearchOption.AllDirectories).Length);
        }
Example #4
0
        public static List <string> GetFilenames(this Ird ird)
        {
            using var decompressedStream = ApiConfig.MemoryStreamManager.GetStream();
            using (var compressedStream = new MemoryStream(ird.Header, false))
            {
                using var gzip = new GZipStream(compressedStream, CompressionMode.Decompress);
                gzip.CopyTo(decompressedStream);
            }

            decompressedStream.Seek(0, SeekOrigin.Begin);
            var reader = new CDReader(decompressedStream, true, true);

            return(reader.GetFiles(reader.Root.FullName, "*.*", SearchOption.AllDirectories)
                   .Distinct()
                   .Select(n => n
                           .TrimStart('\\')
                           .Replace('\\', '/')
                           .TrimEnd('.')
                           ).ToList());
        }
Example #5
0
        /// <summary>
        /// The get files.
        /// </summary>
        public void GetFiles()
        {
            using (var fileStream = new FileStream(this.IsoPath, FileMode.Open))
            {
                DiscFileSystem fs;

                if (UdfReader.Detect(fileStream))
                {
                    fs = new UdfReader(fileStream);
                }
                else
                {
                    fs = new CDReader(fileStream, true);
                }

                // DiscUtils.Iso9660.CDReader reader = new CDReader(fs, true);
                var returnFiles = new List <string>();
                this.Files.AddRange(RecursiveFolders(fs, fs.Root.FullName));
            }
        }
            /// <summary>
            /// Get a spesific file from iso path
            /// </summary>
            /// <param name="file"></param>
            /// <returns></returns>
            public Stream Get_File(string file)
            {
                Stream returnstrm = null;

                if (ISO_File == "")
                {
                    throw new Exception("ISO Path not set");
                }

                using (FileStream isoStream = File.OpenRead(ISO_File))
                {
                    //use disk utils to read iso file
                    CDReader cd = new CDReader(isoStream, true);
                    //look for the specific file naimly the system config file
                    Stream fileStream = cd.OpenFile(file, FileMode.Open);
                    returnstrm = fileStream;
                }

                return(returnstrm);
            }
Example #7
0
        public void HideVersions()
        {
            CDBuilder builder = new CDBuilder();

            builder.UseJoliet = true;
            builder.AddFile("FILE.TXT;1", new byte[] { });

            MemoryStream ms = new MemoryStream();

            SparseStream.Pump(builder.Build(), ms);

            CDReader reader = new CDReader(ms, true, false);

            Assert.Equal("\\FILE.TXT;1", reader.GetFiles("")[0]);
            Assert.Equal("\\FILE.TXT;1", reader.GetFileSystemEntries("")[0]);

            reader = new CDReader(ms, true, true);
            Assert.Equal("\\FILE.TXT", reader.GetFiles("")[0]);
            Assert.Equal("\\FILE.TXT", reader.GetFileSystemEntries("")[0]);
        }
Example #8
0
        public static List <FileRecord> GetFilesystemStructure(this CDReader reader)
        {
            var filenames = reader.GetFiles(reader.Root.FullName, "*.*", SearchOption.AllDirectories).Distinct().Select(n => n.TrimStart('\\')).ToList();
            var result    = new List <FileRecord>();

            foreach (var filename in filenames)
            {
                var clusterRange = reader.PathToClusters(filename);
                if (clusterRange.Length != 1)
                {
                    Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
                }
                if (filename.EndsWith("."))
                {
                    Log.Warn($"Fixing potential mastering error in {filename}");
                }
                result.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
            }
            return(result.OrderBy(r => r.StartSector).ToList());
        }
Example #9
0
 public static IFileSystem GetFileSystem(Stream underlayingStream)
 {
     // Try UDF access first; if that doesn't work, try iso9660
     try
     {
         if (!UdfReader.Detect(underlayingStream))
         {
             throw new ArgumentException("The given stream does not contain a valid UDF filesystem");
         }
         return(new UdfReader(underlayingStream));
     }
     catch
     {
         if (!CDReader.Detect(underlayingStream))
         {
             throw new ArgumentException("The given stream does neither contain a valid UDF nor a valid ISO9660 filesystem");
         }
         return(new CDReader(underlayingStream, true, true));
     }
 }
Example #10
0
        /// <summary>
        ///     Extracts an an ISO file
        /// </summary>
        /// <param name="fileEntry"> </param>
        /// <returns> </returns>
        public async IAsyncEnumerable <FileEntry> ExtractAsync(FileEntry fileEntry, ExtractorOptions options, ResourceGovernor governor)
        {
            using var cd = new CDReader(fileEntry.Content, true);
            var entries = cd.Root.GetFiles("*.*", SearchOption.AllDirectories);

            if (entries != null)
            {
                foreach (var file in entries)
                {
                    var fileInfo = file;
                    governor.CheckResourceGovernor(fileInfo.Length);
                    Stream?stream = null;
                    try
                    {
                        stream = fileInfo.OpenRead();
                    }
                    catch (Exception e)
                    {
                        Logger.Debug("Failed to extract {0} from ISO {1}. ({2}:{3})", fileInfo.Name, fileEntry.FullPath, e.GetType(), e.Message);
                    }
                    if (stream != null)
                    {
                        var name         = fileInfo.Name.Replace('/', Path.DirectorySeparatorChar);
                        var newFileEntry = await FileEntry.FromStreamAsync(name, stream, fileEntry);

                        var innerEntries = Context.ExtractAsync(newFileEntry, options, governor);
                        await foreach (var entry in innerEntries)
                        {
                            yield return(entry);
                        }
                    }
                }
            }
            else
            {
                if (options.ExtractSelfOnFail)
                {
                    yield return(fileEntry);
                }
            }
        }
        // Recursive function that reads all the directories in an .iso file.
        public void recurse_iso(string[] directories, CDReader cd, string iso)
        {
            foreach (var d in directories)
            {
                foreach (var f in cd.GetFiles(d))
                {
                    var index    = f.LastIndexOf('\\');
                    var filename = f.Substring(index + 1, f.Length - index - 1);
                    foreach (var item in search_terms)
                    {
                        if (filename.ToLower().Contains(item))
                        {
                            file_list.Add(new File_Info(iso + f, filename));
                        }
                    }
                }

                var dir = cd.GetDirectories(d);
                recurse_iso(dir, cd, iso);
            }
        }
        // Function that reads .iso files without extracting the file.
        public void read_iso(string iso)
        {
            using (var isoStream = File.Open(iso, FileMode.Open))
            {
                foreach (var item in search_terms)
                {
                    if (iso.ToLower().Contains(item))
                    {
                        var index    = iso.LastIndexOf('\\');
                        var filename = iso.Substring(index + 1, iso.Length - index - 1);
                        file_list.Add(new File_Info(iso, filename));
                        return;
                    }
                }

                var cd   = new CDReader(isoStream, true);
                var root = cd.Root.FullName.ToString();
                var dir  = cd.GetDirectories(root);
                recurse_iso(dir, cd, iso);
            }
        }
        private void ExtractISO_Directory(CDReader cd, string outputFolder, string cd_path)
        {
            var real_directory = string.Format("{0}/{1}", outputFolder, cd_path);

            if (!Directory.Exists(real_directory))
            {
                Directory.CreateDirectory(real_directory);
            }

            var cd_directories = cd.GetDirectories(cd_path);

            foreach (var cd_directory in cd_directories)
            {
                ExtractISO_Directory(cd, outputFolder, cd_directory);
            }

            var cd_files = cd.GetFiles(cd_path);

            foreach (var cd_file in cd_files)
            {
                var fileStream = cd.OpenFile(cd_file, FileMode.Open);
                var real_file  = string.Format("{0}/{1}", outputFolder, cd_file);
                Log($"extracting {cd_file} to {real_file}");

                using (var writerStream = File.OpenWrite(real_file))
                {
                    var max_chunk = 1024;
                    var buffer    = new byte[max_chunk];

                    for (var b = 0; b < fileStream.Length; b += max_chunk)
                    {
                        var amount = (int)Math.Min(max_chunk, fileStream.Length - b);
                        fileStream.Read(buffer, 0, amount);
                        writerStream.Write(buffer, 0, amount);
                    }
                }

                fileStream.Dispose();
            }
        }
        private XenServerPatchAlert GetAlertFromIsoFile(string fileName)
        {
            if (!fileName.EndsWith(Branding.UpdateIso))
            {
                return(null);
            }

            var xmlDoc = new XmlDocument();

            try
            {
                using (var isoStream = File.Open(fileName, FileMode.Open))
                {
                    var cd = new CDReader(isoStream, true);
                    if (cd.Exists("Update.xml"))
                    {
                        using (var fileStream = cd.OpenFile("Update.xml", FileMode.Open))
                        {
                            xmlDoc.Load(fileStream);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                log.ErrorFormat("Exception while reading the update data from the iso file: {0}", exception.Message);
            }

            var elements = xmlDoc.GetElementsByTagName("update");
            var update   = elements.Count > 0 ? elements[0] : null;

            if (update == null || update.Attributes == null)
            {
                return(null);
            }

            var uuid = update.Attributes["uuid"];

            return(uuid != null?Updates.FindPatchAlertByUuid(uuid.Value) : null);
        }
 private void Recursive_CreateDirs(CDReader cd, string dir, Stream fileStreamFrom, Stream fileStreamTo)
 {
     foreach (string directory in cd.GetDirectories(dir))
     {
         Directory.CreateDirectory(TempPath + @"\" + directory);
         if (cd.GetDirectoryInfo(directory).GetFiles().Length > 0)
         {
             foreach (string file in cd.GetFiles(directory))
             {
                 fileStreamFrom = cd.OpenFile(file, FileMode.Open);
                 fileStreamTo   = File.Open(TempPath + @"\" + file, FileMode.OpenOrCreate);
                 fileStreamFrom.CopyTo(fileStreamTo);
                 fileStreamFrom.Close();
                 fileStreamTo.Close();
             }
         }
         if (cd.GetDirectories(directory).Length > 0)
         {
             Recursive_CreateDirs(cd, directory, fileStreamFrom, fileStreamTo);
         }
     }
 }
            /// <summary>
            /// Returns Content ID (PS2 Game ID)
            /// </summary>
            /// <param name="file">ISO Path</param>
            /// <returns></returns>
            public string Read_ContentID(string file)
            {
                using (FileStream isoStream = File.OpenRead(file))
                {
                    //use disk utils to read iso file
                    CDReader cd = new CDReader(isoStream, true);
                    //look for the specific file naimly the system config file
                    Stream fileStream = cd.OpenFile(@"SYSTEM.CNF", FileMode.Open);
                    // Use fileStream...
                    TextReader tr         = new StreamReader(fileStream);
                    string     fullstring = tr.ReadToEnd();//read string to end this will read all the info we need

                    //mine for info
                    string Is = @"\";
                    string Ie = ";";

                    //mine the start and end of the string
                    int start = fullstring.ToString().IndexOf(Is) + Is.Length;
                    int end   = fullstring.ToString().IndexOf(Ie, start);
                    if (end > start)
                    {
                        string PS2Id = fullstring.ToString().Substring(start, end - start);

                        if (PS2Id != string.Empty)
                        {
                            return(PS2Id.Replace(".", "").Replace("_", "-"));

                            Console.WriteLine("PS2 ID Found" + PS2Id);
                        }
                        else
                        {
                            Console.WriteLine("Could not load PS2 ID");
                            throw new Exception("Could not load PS2 ID");
                        }
                    }
                }
                return("");
            }
        public static DiscInfo ToDiscInfo(this Ird ird)
        {
            List <FileRecord> fsInfo;
            var sectorSize = 2048L;

            using (var stream = new MemoryStream())
            {
                using (var headerStream = new MemoryStream(ird.Header))
                    using (var gzipStream = new GZipStream(headerStream, CompressionMode.Decompress))
                    {
                        gzipStream.CopyTo(stream);
                    }
                stream.Seek(0, SeekOrigin.Begin);
                var reader = new CDReader(stream, true, true);
                fsInfo     = reader.GetFilesystemStructure();
                sectorSize = reader.ClusterSize;
            }
            var checksums = ird.Files.ToDictionary(f => f.Offset, f => f.Md5Checksum.ToHexString());

            return(new DiscInfo
            {
                ProductCode = ird.ProductCode,
                DiscVersion = ird.GameVersion,
                DiscKeyRawData = ird.Data1.ToHexString(),
                DiscKey = Decrypter.DecryptDiscKey(ird.Data1).ToHexString(),
                Files = fsInfo.ToDictionary(
                    f => f.Filename,
                    f => new FileInfo
                {
                    Offset = f.StartSector * sectorSize,
                    Size = f.Length,
                    Hashes = new Dictionary <string, string>
                    {
                        ["MD5"] = checksums[f.StartSector],
                    }
                })
            });
        }
        public void Attributes()
        {
            // Start time rounded down to whole seconds
            DateTime start = DateTime.UtcNow;

            start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second);

            CDBuilder builder = new CDBuilder();

            builder.AddDirectory("Foo");
            CDReader fs  = new CDReader(builder.Build(), false);
            DateTime end = DateTime.UtcNow;

            DiscDirectoryInfo di = fs.GetDirectoryInfo("Foo");

            Assert.Equal(FileAttributes.Directory | FileAttributes.ReadOnly, di.Attributes);
            Assert.True(di.CreationTimeUtc >= start);
            Assert.True(di.CreationTimeUtc <= end);
            Assert.True(di.LastAccessTimeUtc >= start);
            Assert.True(di.LastAccessTimeUtc <= end);
            Assert.True(di.LastWriteTimeUtc >= start);
            Assert.True(di.LastWriteTimeUtc <= end);
        }
Example #19
0
 private void metroListView1_MouseDoubleClick(object sender, MouseEventArgs e)
 {
     if (metroListView1.Items.Count > 0)
     {
         if (metroListView1.SelectedItems[0].SubItems[1].Text == "Directory")
         {
             string item = metroListView1.SelectedItems[0].Text;
             using (FileStream ISOStream = File.Open(openFileDialog1.FileName, FileMode.Open))
             {
                 CDReader Reader = new CDReader(ISOStream, true, true);
                 metroListView1.Items.Clear();
                 GoToDirectory(Reader.Root, textBox1.Text, item, currentFolder);
             }
         }
         else if(metroListView1.SelectedItems[0].SubItems[1].Text == "File")
         {
             string runfile = openFileDialog1.FileName.Replace(".iso", "") + "\\" + textBox1.Text + metroListView1.SelectedItems[0].Text;
             if (!Directory.Exists(runfile))
             ExtractISO(openFileDialog1.SafeFileName, openFileDialog1.FileName.Replace(openFileDialog1.SafeFileName, ""));
             Process.Start(runfile);
         }
     }
 }
Example #20
0
        public Byte[] ReadAllByte(String FileSource)
        {
            Byte[]     result  = { 0x0 };
            FileStream FileISO = File.Open(FileName, FileMode.Open, FileAccess.Read);

            try
            {
                CDReader     ReaderISO     = new CDReader(FileISO, true);
                SparseStream _SourceStream = ReaderISO.OpenFile(FileSource, FileMode.Open, FileAccess.Read);
                Byte[]       _ReadAllByte  = new Byte[_SourceStream.Length];
                _SourceStream.Read(_ReadAllByte, 0, _ReadAllByte.Length);
                result = _ReadAllByte;
                _SourceStream.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("-----------------------------------------------------");
                Console.WriteLine("ReadAllByte(" + FileSource + ")");
                Console.WriteLine(ex.Message);
                Console.WriteLine("-----------------------------------------------------");
            }
            FileISO.Close();
            return(result);
        }
Example #21
0
 public PSPGame(String iso)
 {
     Readable = true;
     try
     {
         FileStream FileISO   = File.Open(iso, FileMode.Open, FileAccess.Read);
         CDReader   ReaderISO = new CDReader(FileISO, true);
         FileName = iso;
         FileSize = FileISO.Length;
         if (!ReaderISO.FileExists("PSP_GAME\\PARAM.SFO"))
         {
             throw new NotImplementedException();
         }
         FileISO.Close();
     }
     catch (Exception ex)
     {
         Readable = false;
         Console.WriteLine("-----------------------------------------------------");
         Console.WriteLine("PSPGame(" + iso + ")");
         Console.WriteLine(ex.Message);
         Console.WriteLine("-----------------------------------------------------");
     }
 }
Example #22
0
        /// <summary>
        /// TODO MIT license friendly
        /// </summary>
        /// <param name="destinationFolder"></param>
        public void RipNew(string destinationFolder)
        {
            RippedDirectory = destinationFolder;
            RippedCatPath   = Path.GetDirectoryName(ImageBinPath) + "\\" + Path.GetFileNameWithoutExtension(ImageBinPath) + ".cat";
            if (Path.GetExtension(ImageBinPath).ToLower() != ".bin")
            {
                return;
            }
            if (!File.Exists(ImageBinPath))
            {
                return;
            }

            using (FileStream fileStream = File.Open(ImageCuePath, FileMode.Open))
            {
                CDReader cdReader = new CDReader(fileStream, true);
                string[] files    = GetFiles(cdReader.Root);

                foreach (string file in files)
                {
                    Console.WriteLine(file);
                }
            }
        }
Example #23
0
        static bool ProcessRecoveryISO(Stream isoStream, string outputPath, bool extractFiles = true, bool consoleOutput = true)
        {
            if (ProcessRecoveryGDF(isoStream, outputPath, extractFiles, consoleOutput))
            {
                return(true);
            }

            DiscUtils.Vfs.VfsFileSystemFacade vfs = new CDReader(isoStream, true, false);
            if (!vfs.FileExists("recctrl.bin"))
            {
                vfs = new UdfReader(isoStream);
            }
            if (!vfs.FileExists("recctrl.bin"))
            {
                Console.WriteLine("Failed to find recctrl.bin inside image!");
                return(false);
            }

            using (var reader = new BinaryReader(vfs.OpenFile("recctrl.bin", FileMode.Open)))
            {
                Stream dataStream = null;
                if (extractFiles)
                {
                    dataStream = vfs.OpenFile("recdata.bin", FileMode.Open);
                }

                bool res = ProcessRecovery(reader, dataStream, outputPath, consoleOutput);

                if (dataStream != null)
                {
                    dataStream.Close();
                }

                return(res);
            }
        }
Example #24
0
        private string Run(int revision, string additionalFilePath, bool autoStartChecked)
        {
            string filename = string.Format("bootcd-{0}-dbg", revision);

            string filename7z = filename + ".7z";
            string filenameIso = filename + ".iso";

            if (!File.Exists(filenameIso))
            {
                string filename7zTemp = filename7z + ".temp";
                string filenameIsoTemp = filenameIso + ".temp";

                if (!File.Exists(filename7z))
                {
                    File.Delete(filename7zTemp);

                    WebClient wc = new WebClient();
                    try
                    {
                        wc.DownloadFile(revToUrl[revision], filename7zTemp);
                    }
                    catch (WebException)
                    {
                        return "File download failed:\n  '" + revToUrl[revision] + "'";
                    }

                    File.Move(filename7zTemp, filename7z);
                }

                File.Delete(filenameIsoTemp);

                FileStream isotmpfs = File.Create(filenameIsoTemp);
                FileStream szfs = File.Open(filename7z, FileMode.Open, FileAccess.Read);
                SevenZipExtractor sze = new SevenZipExtractor(szfs);
                sze.ExtractFile(filenameIso, isotmpfs);
                isotmpfs.Close();
                szfs.Close();

                File.Move(filenameIsoTemp, filenameIso);
                File.Delete(filename7z);
            }


            string vmName = string.Format("ReactOS_r{0}", revision);
            string diskName = Environment.CurrentDirectory + "\\" + vmName + "\\" + vmName + ".vdi";

            if (File.Exists(diskName))
            {
                FileStream fs = null;
                try
                {
                    fs = File.Open(diskName, FileMode.Open, FileAccess.Read, FileShare.None);
                }
                catch (IOException)
                {
                    return "Virtual machine '" + vmName + "' is already running";
                }
                finally
                {
                    if (fs != null)
                        fs.Close();
                }
            }


            string filenameIsoUnatt = filename + "_unatt.iso";
            string filenameIsoUnattTemp = filenameIsoUnatt + ".temp";
            File.Delete(filenameIsoUnattTemp);
            File.Delete(filenameIsoUnatt);

            FileStream isofs = File.Open(filenameIso, FileMode.Open, FileAccess.Read);
            CDReader cdr = new CDReader(isofs, true);
            CDBuilder cdb = new CDBuilder();
            cdb.VolumeIdentifier = cdr.VolumeLabel;
            CloneCdDirectory("", cdr, cdb);

            if (!File.Exists("unattend.inf"))
                File.WriteAllText("unattend.inf", RosRegTest.Resources.unattend, Encoding.ASCII);

            string additionalFileName = null;
            if (additionalFilePath != null)
                additionalFileName = Path.GetFileName(additionalFilePath);

            string unattText = File.ReadAllText("unattend.inf", Encoding.ASCII);
            if (autoStartChecked && (additionalFileName != null))
                unattText = unattText + "[GuiRunOnce]\n" + "cmd.exe /c start d:\\" + additionalFileName + "\n\n";

            cdb.AddFile("reactos\\unattend.inf", Encoding.ASCII.GetBytes(unattText));
            if (additionalFileName != null)
                cdb.AddFile(additionalFileName, additionalFilePath);

            Stream bootImgStr = cdr.OpenBootImage();
            cdb.SetBootImage(bootImgStr, cdr.BootEmulation, cdr.BootLoadSegment);
            bootImgStr.Close();

            cdb.Build(filenameIsoUnattTemp);
            isofs.Close();

            File.Move(filenameIsoUnattTemp, filenameIsoUnatt);


            string fullIsoName = Environment.CurrentDirectory + "\\" + filenameIsoUnatt;
            string deleteVmCmd = string.Format("unregistervm --name {0}", vmName);
            string createVmCmd = string.Format(
                "createvm --name {0} --basefolder {1} --ostype WindowsXP --register",
                vmName, Environment.CurrentDirectory);
            string modifyVmCmd = string.Format("modifyvm {0} --memory 512 --vram 16 --nictype1 Am79C973 --audio none --boot1 disk --boot2 dvd", vmName);
            string storageCtlCmd = string.Format("storagectl {0} --name \"IDE Controller\" --add ide", vmName);
            string createMediumCmd = string.Format("createmedium disk --filename {0} --size 4096", diskName);
            string storageAttachCmd1 = string.Format("storageattach {0} --port 0 --device 0 --storagectl \"IDE Controller\" --type hdd --medium {1}", vmName, diskName);
            string storageAttachCmd2 = string.Format("storageattach {0} --port 1 --device 0 --storagectl \"IDE Controller\" --type dvddrive --medium {1}", vmName, fullIsoName);
            string startCmd = string.Format("startvm {0}", vmName);

            Exec(vboxManagePath, deleteVmCmd);
            Exec(vboxManagePath, createVmCmd);
            Exec(vboxManagePath, modifyVmCmd);
            Exec(vboxManagePath, storageCtlCmd);
            Exec(vboxManagePath, createMediumCmd);
            Exec(vboxManagePath, storageAttachCmd1);
            Exec(vboxManagePath, storageAttachCmd2);
            Exec(vboxManagePath, startCmd);

            return null;
        }
Example #25
0
        public static GameEntry FindGameInfo(string srcIso, string name = "PS1 Game")
        {
            var regex     = new Regex("(S[LC]\\w{2})[_-](\\d{3})\\.(\\d{2})");
            var bootRegex = new Regex("BOOT\\s*=\\s*cdrom:\\\\?(?:.*?\\\\)?(S[LC]\\w{2}[_-]?\\d{3}\\.\\d{2});1");

            GameEntry game = null;

            using (var stream = new FileStream(srcIso, FileMode.Open))
            {
                var cdReader = new CDReader(stream, false, 2352);

                string gameId = "";

                //foreach (var file in cdReader.GetFiles("\\"))
                //{
                //    var filename = file.Substring(1, file.LastIndexOf(";"));
                //    var match = regex.Match(filename);
                //    if (match.Success)
                //    {
                //        gameId = $"{match.Groups[1].Value}{match.Groups[2].Value}{match.Groups[3].Value}";
                //        break;
                //    }
                //}

                foreach (var file in cdReader.GetFiles("\\"))
                {
                    var filename = file.Substring(1, file.LastIndexOf(";") - 1);
                    if (filename == "SYSTEM.CNF")
                    {
                        using (var datastream = cdReader.OpenFile(file, FileMode.Open))
                        {
                            datastream.Seek(24, SeekOrigin.Begin);
                            var textReader = new StreamReader(datastream);
                            var bootLine   = textReader.ReadLine();
                            var bootmatch  = bootRegex.Match(bootLine);
                            if (bootmatch.Success)
                            {
                                var match = regex.Match(bootmatch.Groups[1].Value);
                                if (match.Success)
                                {
                                    gameId = $"{match.Groups[1].Value}{match.Groups[2].Value}{match.Groups[3].Value}";

                                    GameEntry gm = new GameEntry();
                                    gm.GameID         = gameId;
                                    gm.ScannerID      = gameId;
                                    gm.SaveFolderName = gameId;
                                    switch (gameId[2]) // Leave the option avalible for the user to correct it
                                    {
                                    case 'J':
                                        gm.Format = "NTSC";
                                        break;

                                    case 'U':
                                        gm.Format = "NTSC";
                                        break;

                                    case 'E':
                                        gm.Format = "PAL";
                                        break;
                                    }
                                    game = gm;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return(game);
        }
Example #26
0
        public static VirtualDirectory ToVirtualDirectory(this CDReader isoFileSystem)
        {
            string teststring = isoFileSystem.Root.FullName;

            return(ToVirtualFileSystemEntry(isoFileSystem, isoFileSystem.Root.FullName) as VirtualDirectory);
        }
Example #27
0
 /// <inheritdoc/>
 public string GetInternalName(Stream romStream)
 {
     romStream.Seek(0, SeekOrigin.Begin);
     using var reader = new CDReader(romStream, true);
     return(reader.VolumeLabel);
 }
Example #28
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="ApplicationException"></exception>
        public void ExtractBin(string cueFileName)
        {
            if (!Directory.Exists(Directory.GetCurrentDirectory() + @"\" + _outFileNameBase))
            {
                Directory.CreateDirectory(Directory.GetCurrentDirectory() + @"\" + _outFileNameBase);
            }
            var save_dir = Directory.GetCurrentDirectory() + @"\" + _outFileNameBase;

            try
            {
                CueFile cueFile;
                try
                {
                    cueFileName = Path.ChangeExtension(cueFileName, CueExtension);
                    cueFile     = new CueFile(cueFileName);
                }
                catch (Exception e)
                {
                    throw new ApplicationException($"Could not read CUE {cueFileName}:\n{e.Message}");
                }

                Stream binStream;
                try
                {
                    File.Copy(cueFile.BinFileName, save_dir + @"\" + _outFileNameBase + ".bin");
                    binStream = File.OpenRead(cueFile.BinFileName);
                }
                catch (Exception e)
                {
                    throw new ApplicationException($"Could not open BIN {cueFile.BinFileName}: {e.Message}");
                }

                Console.WriteLine(Environment.NewLine + "Writing tracks:");
                foreach (Track curTrack in cueFile.TrackList)
                {
                    Console.WriteLine(curTrack.Modes);
                    Console.WriteLine(curTrack.FileExtension);
                    Console.WriteLine(cueFile.TrackList.Count);
                    // Include track number when more than 1 track.

                    if (cueFile.TrackList.Count > 1)
                    {
                        _outFileName =
                            $"{_outFileNameBase}{curTrack.TrackNumber:00}.{curTrack.FileExtension.ToString().ToLower()}";
                    }
                    else
                    {
                        _outFileName = $"{_outFileNameBase}.{curTrack.FileExtension.ToString().ToLower()}";
                    }
                    curTrack.Write(binStream, _outFileName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("discutils");
            using (FileStream isoStream = File.OpenRead(_outFileName))
            {
                CDReader cd = new CDReader(isoStream, false);
                Console.WriteLine(cd.Root.FullName);

                string[] files   = cd.GetFiles(cd.Root.FullName);
                string[] dirs    = cd.GetDirectories(cd.Root.FullName);
                bool     mrgdone = false;

                foreach (string c in files)
                {
                    Console.WriteLine(c);
                    if (c == @"\SLUS_014.11;1")
                    {
                        FileStream   fs  = File.Create(save_dir + @"\SLUS_014.11");
                        SparseStream isf = cd.OpenFile(c, FileMode.Open);
                        byte[]       dat = new byte[isf.Length];

                        int result = AsyncContext.Run(() => isf.ReadAsync(dat, 0, (int)isf.Length));

                        Task task = Task.Run(async() => { await fs.WriteAsync(dat, 0, dat.Length); });
                        task.Wait();
                        fs.Close();
                    }

                    foreach (string e in cd.GetFiles("\\DATA"))
                    {
                        Console.WriteLine(e);
                        if (e == @"\DATA\WA_MRG.MRG;1" && !mrgdone)
                        {
                            FileStream   fs     = File.Create(save_dir + @"\WA_MRG.MRG");
                            SparseStream isf    = cd.OpenFile(e, FileMode.Open);
                            byte[]       dat    = new byte[isf.Length];
                            int          result = AsyncContext.Run(() => isf.ReadAsync(dat, 0, (int)isf.Length));
                            Task         task   = Task.Run(async() => { await fs.WriteAsync(dat, 0, dat.Length); });
                            task.Wait();
                            mrgdone = true;
                            fs.Close();
                            break;
                        }
                    }

                    Static.SlusPath = save_dir + @"\SLUS_014.11";
                    Static.WaPath   = save_dir + @"\WA_MRG.MRG";
                    Static.IsoPath  = save_dir + @"\" + _outFileNameBase + ".bin";
                }
                isoStream.Close();
                File.Delete(_outFileName);
            }
        }
Example #29
0
        public async Task PublishAsync(CancellationToken aCancellationToken, TextWriter aOutputPaneWriter)
        {
            var xProjectProperties = await ProjectProperties.GetConfigurationGeneralPropertiesAsync().ConfigureAwait(false);

            var xOutputType = await xProjectProperties.OutputType.GetEvaluatedValueAtEndAsync().ConfigureAwait(false);

            var xOutputISO = await xProjectProperties.OutputISO.GetEvaluatedValueAtEndAsync().ConfigureAwait(false);

            xOutputISO = ConfiguredProject.UnconfiguredProject.MakeRooted(xOutputISO);

            if (String.Equals(xOutputType, OutputTypeValues.Bootable, StringComparison.OrdinalIgnoreCase))
            {
                if (mPublishSettings == null)
                {
                    await aOutputPaneWriter.WriteAsync("Publish settings are null!").ConfigureAwait(false);

                    return;
                }

                switch (mPublishSettings.PublishType)
                {
                case PublishType.ISO:
                    await aOutputPaneWriter.WriteLineAsync("Publishing ISO!").ConfigureAwait(false);

                    if (String.IsNullOrWhiteSpace(mPublishSettings.PublishPath))
                    {
                        throw new Exception($"Invalid publish path! Publish path: '{mPublishSettings.PublishPath}'");
                    }

                    File.Copy(xOutputISO, mPublishSettings.PublishPath, true);

                    break;

                case PublishType.USB:
                    await aOutputPaneWriter.WriteLineAsync("Publishing USB!").ConfigureAwait(false);

                    DriveInfo xDriveInfo;

                    try
                    {
                        xDriveInfo = new DriveInfo(mPublishSettings.PublishPath);
                    }
                    catch (ArgumentException)
                    {
                        throw new Exception($"Invalid drive letter! Drive letter: '{mPublishSettings.PublishPath}'");
                    }

                    // todo: format USB drive if requested? how?

                    var xDrivePath = xDriveInfo.RootDirectory.FullName;

                    using (var xStream = File.OpenRead(xOutputISO))
                    {
                        using (var xReader = new CDReader(xStream, true))
                        {
                            foreach (var xFile in xReader.GetFiles(""))
                            {
                                using (var xFileStream = xReader.OpenFile(xFile, FileMode.Open))
                                {
                                    using (var xNewFile = File.Create(Path.Combine(xDrivePath, Path.GetFileName(xFile))))
                                    {
                                        await xFileStream.CopyToAsync(xNewFile).ConfigureAwait(false);
                                    }
                                }
                            }
                        }
                    }

                    break;

                default:
                    await aOutputPaneWriter.WriteLineAsync(
                        $"Unknown publish type! Publish type: '{mPublishSettings.PublishType}'").ConfigureAwait(false);

                    break;
                }
            }
            else
            {
                await ConfiguredProject.Services.Build.BuildAsync(
                    ImmutableArray.Create("Publish"), CancellationToken.None, true).ConfigureAwait(false);
            }

            await aOutputPaneWriter.WriteLineAsync("Publish successful!").ConfigureAwait(false);
        }
        public override void Extract(string inputPath, string outputPath)
        {
            //Needed to build
            File.Copy(inputPath, ModLoaderGlobals.ToolsPath + "Game.iso");

            using (FileStream isoStream = File.Open(inputPath, FileMode.Open))
            {
                FileInfo   isoInfo = new FileInfo(inputPath);
                CDReader   cd;
                FileStream tempbin = null;
                if (Path.GetExtension(inputPath).ToLower() == ".bin")
                {
                    FileStream binconvout = new FileStream(ModLoaderGlobals.BaseDirectory + "binconvout.iso", FileMode.Create, FileAccess.Write);
                    PSX2ISO.Run(isoStream, binconvout);
                    binconvout.Close();
                    tempbin = new FileStream(ModLoaderGlobals.BaseDirectory + "binconvout.iso", FileMode.Open, FileAccess.Read);
                    cd      = new CDReader(tempbin, true);
                }
                else
                {
                    cd = new CDReader(isoStream, true);
                }
                //ModLoaderGlobals.ISO_Label = cd.VolumeLabel;

                /* Sometimes doesn't work?
                 * if (isoInfo.Length * 2 > GetTotalFreeSpace(ModLoaderGlobals.TempPath.Substring(0, 3)))
                 * {
                 *  cd.Dispose();
                 *  throw new IOException("Extraction error: Not enough hard drive space where this program is!");
                 * }
                 * if (isoInfo.Length * 2 > GetTotalFreeSpace(ModLoaderGlobals.OutputPath.Substring(0, 3)))
                 * {
                 *  cd.Dispose();
                 *  throw new IOException("Extraction error: Not enough hard drive space in the output path!");
                 * }
                 */

                //fileStream = cd.OpenFile(@"SYSTEM.CNF", FileMode.Open);

                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                //Extracting ISO
                Stream fileStreamFrom = null;
                Stream fileStreamTo   = null;
                if (cd.GetDirectories("").Length > 0)
                {
                    foreach (string directory in cd.GetDirectories(""))
                    {
                        Directory.CreateDirectory(outputPath + directory);
                        if (cd.GetDirectoryInfo(directory).GetFiles().Length > 0)
                        {
                            foreach (string file in cd.GetFiles(directory))
                            {
                                fileStreamFrom = cd.OpenFile(file, FileMode.Open);
                                string filename = outputPath + file;
                                filename     = filename.Replace(";1", string.Empty);
                                fileStreamTo = File.Open(filename, FileMode.OpenOrCreate);
                                fileStreamFrom.CopyTo(fileStreamTo);
                                fileStreamFrom.Close();
                                fileStreamTo.Close();
                            }
                        }
                        if (cd.GetDirectories(directory).Length > 0)
                        {
                            Recursive_CreateDirs(cd, directory, fileStreamFrom, fileStreamTo);
                        }
                    }
                }
                if (cd.GetDirectoryInfo("").GetFiles().Length > 0)
                {
                    foreach (string file in cd.GetFiles(""))
                    {
                        fileStreamFrom = cd.OpenFile(file, FileMode.Open);
                        string filename = outputPath + "/" + file;
                        filename     = filename.Replace(";1", string.Empty);
                        fileStreamTo = File.Open(filename, FileMode.OpenOrCreate);
                        fileStreamFrom.CopyTo(fileStreamTo);
                        fileStreamFrom.Close();
                        fileStreamTo.Close();
                    }
                }

                cd.Dispose();

                if (tempbin != null)
                {
                    tempbin.Dispose();
                    File.Delete(ModLoaderGlobals.BaseDirectory + "binconvout.iso");
                }
            }
        }