private void Encrypt_Click(object sender, RoutedEventArgs e) { foreach (string item in File2.GetDirectories(root: "", path, rootDir + Global.DownloadFolder)) { if (File.Exists($"{item}/info.json")) { JObject j = JObject.Parse(File.ReadAllText($"{item}/info.json")); j["encrypted"] = true; File.WriteAllText($"{item}/info.json", j.ToString()); } string[] files = Directory.GetFiles(item); foreach (string file in files) { if (Path.GetFileName(file) == "info.json") { continue; } if (Path.GetFileName(file) == "info.txt") { continue; } if (Path.GetExtension(file) == ".lock") { continue; } byte[] org = File.ReadAllBytes(file); byte[] enc = FileEncrypt.Default(org); File.Delete(file); File.WriteAllBytes(file + ".lock", enc); } } MessageBox.Show("전체 암호화 완료"); }
/// <summary> /// Get file from patch contents and put it into mod folder /// </summary> /// <param name="bnkFilePath"></param> /// <param name="sourceDirectory"></param> /// <param name="packedFileName"></param> /// <param name="modFolder"></param> private static void _GetContents(string bnkFilePath, string sourceDirectory, string packedFileName, string modFolder) { if (sourceDirectory == null) { sourceDirectory = ""; } FileInfo fi = new FileInfo(bnkFilePath); string sourceFileName = string.Concat(PatchHelper.CurrentPath, @"\", sourceDirectory, @"\", packedFileName); // BUG_84: suffix added to folder string modSubFolder = string.Concat(fi.Name, _SUFFIX_PACKED); string destinationFileName = string.Concat(modFolder, @"\", modSubFolder, @"\", packedFileName); // If file with same name already exists in repo, it is overwritten fi = new FileInfo(destinationFileName); if (fi.Directory == null) { throw new Exception("Invalid file name: " + destinationFileName); } if (!Directory.Exists(fi.Directory.FullName)) { Directory.CreateDirectory(fi.Directory.FullName); } // Removing read-only flag on destination file if (fi.Exists) { File2.RemoveAttribute(destinationFileName, FileAttributes.ReadOnly); } File.Copy(sourceFileName, destinationFileName, true); }
/// <summary> /// Defines Picture tab contents /// </summary> private void _UpdatePictureTab() { // Searching for picture in deploy folder string deployFolder = Program.ApplicationSettings.PatchEditorLastDeployLocation; if (!string.IsNullOrEmpty(deployFolder) && Directory.Exists(deployFolder)) { string pictureFile = deployFolder + LibraryConstants.FILE_MNP_BACKGROUND_PICTURE; notGeneratedLabel.Visible = false; if (File.Exists(pictureFile)) { string tempFolder = File2.SetTemporaryFolder(null, LibraryConstants.FOLDER_TEMP, true); string workingFile = tempFolder + LibraryConstants.FILE_MNP_BACKGROUND_PICTURE; File.Copy(pictureFile, workingFile, true); picPanel.BackgroundImage = Image.FromFile(workingFile); } else { picPanel.BackgroundImage = Resources.nopic; } } else { picPanel.BackgroundImage = null; notGeneratedLabel.Visible = true; } }
/// <summary> /// Crée une copie de sauvegarde du fichier spécifié. /// Les dates de création/modification restent inchangées. /// </summary> /// <param name="fileName">Nom du fichier à sauvegarder</param> /// <param name="copyFileName">Nom de la copie</param> public static void BackupFile(string fileName, string copyFileName) { try { // Vérifications if (fileName == null || copyFileName == null || fileName.Equals(copyFileName)) { throw new Exception(_ERROR_BACKUP_PARAMS); } // Copie avec préservation de la date de modification FileInfo sourceInfo = new FileInfo(fileName); DateTime modDate = sourceInfo.LastWriteTime; File.Copy(fileName, copyFileName, true); File2.RemoveAttribute(copyFileName, FileAttributes.ReadOnly); new FileInfo(copyFileName) { LastWriteTime = modDate }; File2.AddAttribute(copyFileName, FileAttributes.ReadOnly); } catch (Exception ex) { string errorMessage = string.Format(_ERROR_BACKUP, fileName, copyFileName); throw new Exception(errorMessage, ex); } }
private void Hitomi_Download_Click(object sender, RoutedEventArgs e) { Task.Factory.StartNew(() => { string filename = File2.GetDownloadTitle(File2.SaftyFileName(h.name)); if (!Directory.Exists($"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}")) { Directory.CreateDirectory($"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}"); } Directory.CreateDirectory($"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}/{filename}"); h.dir = $"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}/{filename}"; h.Save($"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}/{filename}/info.json"); for (int i = 0; i < h.files.Length; i++) { string file = h.files[i]; WebClient wc = new WebClient(); wc.Headers.Add("referer", "https://hitomi.la/"); if (!File.Exists($"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}/{filename}/{i}.jpg")) { h.encrypted = Global.AutoFileEn; if (Global.AutoFileEn) { FileEncrypt.DownloadAsync(new Uri(file), $"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}/{filename}/{i}.jpg.lock"); } else { wc.DownloadFileAsync(new Uri(file), $"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}/{filename}/{i}.jpg"); } } } Process.Start($"{AppDomain.CurrentDomain.BaseDirectory}/{Global.DownloadFolder}/{filename}"); }); }
private void Decrypt_Click(object sender, RoutedEventArgs e) { bool err = FileDecrypt.TryFiles(h.dir); if (err) { while (true) { InputBox box = new InputBox("비밀번호를 입력해주세요.", "비밀번호가 맞지 않습니다.", ""); string password = box.ShowDialog(); if (box.canceled) { return; } if (FileDecrypt.TryFiles(h.dir, SHA256.Hash(password), excepts: new string[] { ".txt", ".json" })) { break; } } } h.thumb = ImageProcessor.ProcessEncrypt(File2.GetImages(h.dir).First()); h.files = h.files.Select(x => Path.Combine(Path.GetDirectoryName(x), Path.GetFileNameWithoutExtension(x))).ToArray(); h.encrypted = false; thumbNail.Source = h.thumb; thumbNail.ToolTip = GetToolTip(panel.Height); Process.Start(h.dir); }
private void Decrypt_Click(object sender, RoutedEventArgs e) { foreach (string item in File2.GetDirectories(root: "", path, rootDir + Global.DownloadFolder)) { if (File.Exists($"{path}/info.json")) { JObject j = JObject.Parse(File.ReadAllText($"{path}/info.json")); j["encrypted"] = false; File.WriteAllText($"{path}/info.json", j.ToString()); } string[] files = Directory.GetFiles(item); foreach (string file in files) { try { byte[] org = File.ReadAllBytes(file); byte[] enc = FileDecrypt.Default(org); File.Delete(file); File.WriteAllBytes(Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)), enc); } catch { } } } MessageBox.Show("전체 복호화 완료"); }
/// <summary> /// Restaure le fichier d'origine depuis la sauvegarde spécifiée /// </summary> /// <param name="fileName">nom du fichier de sauvegarde</param> private bool _RestoreFile(string fileName) { bool isModified = false; string message; if (Regex.IsMatch(fileName, TduFile.BACKUP_FILENAME_PATTERN, RegexOptions.IgnoreCase)) { // Backup -> restauration string originalFileName = File2.ChangeExtensionOfFilename(fileName, null); message = string.Format(_QUESTION_RESTORE, originalFileName, fileName); DialogResult dr = MessageBoxes.ShowQuestion(this, message, MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { // Opération de restauration Tools.RestoreFile(fileName, originalFileName); isModified = true; } } else { // Pour les autres fichiers on interdit la restauration message = string.Format(_ERROR_NOT_A_BACKUP, fileName); MessageBoxes.ShowWarning(this, message); } return(isModified); }
/// <summary> /// Saves the current file to disk. /// </summary> public override void Save() { try { byte[] xmlData; // Saving XML then re-building config file _Doc.Save(_WorkingFileName); using ( BinaryReader reader = new BinaryReader(new FileStream(_WorkingFileName, FileMode.Open, FileAccess.Read))) { xmlData = reader.ReadBytes((int)reader.BaseStream.Length); } using ( BinaryWriter writer = new BinaryWriter(new FileStream(_WorkingFileName, FileMode.Create, FileAccess.Write))) { writer.Write(xmlData); writer.Write(_DirtyData); } // File encryption File2.RemoveAttribute(_FileName, FileAttributes.ReadOnly); XTEAEncryption.Encrypt(_WorkingFileName, _FileName); } catch (Exception ex) { throw new Exception("Unable to save file: " + _FileName, ex); } }
/// <summary> /// Get file from patch contents and put it into mod repository /// </summary> /// <param name="fileName"></param> /// <param name="fileType"></param> /// <param name="sourceDirectory"></param> /// <param name="modFolder"></param> private static void _GetContents(string fileName, string fileType, string sourceDirectory, string modFolder) { string subFolder = ""; if (FileTypeVP.TYPE_GAUGES_HIGH.Equals(fileType)) { subFolder = InstallHelper.FOLDER_HI_GAUGE_PART; } else if (FileTypeVP.TYPE_GAUGES_LOW.Equals(fileType)) { subFolder = InstallHelper.FOLDER_LO_GAUGE_PART; } string sourceFileName = PatchHelper.CurrentPath + @"\" + sourceDirectory + @"\" + fileName; string destinationFileName = modFolder + subFolder + fileName; // Removing read-only flag on destination file if (File.Exists(destinationFileName)) { File2.RemoveAttribute(destinationFileName, FileAttributes.ReadOnly); } // If file with same name already exists in repo, it is overwritten File.Copy(sourceFileName, destinationFileName, true); }
/// <summary> /// Prepares a packed file for viewing/editing. can be used as stand-alone to get files without creating any task. /// </summary> /// <param name="bnk">BNK file</param> /// <param name="packedFilePath">Path of packed file to prepare</param> /// <returns>Full path of extracted file</returns> public string PrepareFile(BNK bnk, string packedFilePath) { string returnPath = null; if (bnk == null || string.IsNullOrEmpty(packedFilePath)) { return(returnPath); } // Working folder string workFolder = File2.SetTemporaryFolder(null, LibraryConstants.FOLDER_TEMP, true); if (workFolder == null) { throw new Exception(ERROR_CODE_TEMP_FOLDER); } // Extracting packed file into working folder string packedFileName = bnk.GetPackedFileName(packedFilePath); returnPath = string.Format(@"{0}\{1}", workFolder, packedFileName); bnk.ExtractPackedFile(packedFilePath, returnPath, false); // Removing attributes on file File.SetAttributes(returnPath, FileAttributes.Normal); return(returnPath); }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) { LabelSetup(); this.Background = new SolidColorBrush(Global.background); MainPanel.Children.Clear(); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } int pages = Directory.GetDirectories(path).Length / 25 + 1; for (int i = 0; i < pages; i++) { Page_Index.Items.Add(i + 1); } Page_Index.SelectedIndex = 0; Page_ItemCount.SelectedIndex = 3; SearchMode2.SelectedIndex = 0; DelayRegistEvents(); if (Global.DownloadFolder != "hitomi_downloaded") { new TaskFactory().StartNew(() => LoadHitomi(File2.GetDirectories(root: "", path, rootDir + Global.DownloadFolder))); } else { new TaskFactory().StartNew(() => LoadHitomi(path)); } }
/// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="type"></param> /// <param name="backupDirectory"></param> /// <param name="tduFolder"></param> private static void _UninstallFile(string name, string type, string backupDirectory, string tduFolder) { string sourceSubFolder = ""; if (FileTypeVP.TYPE_GAUGES_HIGH.Equals(type)) { sourceSubFolder = InstallHelper.FOLDER_HI_GAUGE_PART; } else if (FileTypeVP.TYPE_GAUGES_LOW.Equals(type)) { sourceSubFolder = InstallHelper.FOLDER_LO_GAUGE_PART; } string sourceFileName = string.Concat(backupDirectory, sourceSubFolder, name); string destinationFileName = string.Concat(tduFolder, name); // Removing read-only flag on destination file if (File.Exists(destinationFileName)) { File2.RemoveAttribute(destinationFileName, FileAttributes.ReadOnly); } // Backup file is kept File.Copy(sourceFileName, destinationFileName, true); }
/// <summary> /// Transforme un nom d'objet ou de fichier de façon à ce qu'il respecte une longueur de 8 caractères maxi et son unicité. /// This transformation is used with 3D meshes, materials, texture names. /// </summary> /// <param name="objectName">nom à convertir, sans chemin s'il s'agit d'un fichier</param> /// <returns>Un nom unique, ou null s'il s'agit d'une chaîne vide ou nulle</returns> public static string NormalizeName(string objectName) { if (string.IsNullOrEmpty(objectName)) { return(null); } // Récupération du nom sans extension string name = File2.GetNameFromFilename(objectName); if (name.Length <= 8) { // Length <= 8: string is filled with 0s for (int i = name.Length; i < 8; i++) { name += "\0"; } // BUG_: name is returned return(name); } // Récupération des caractères dépassant le 8e char[] nameChars = name.Substring(0, 8).ToCharArray(); char[] overFlow = name.Substring(8).ToCharArray(); // Pour chaque caractère dépassant, on va ajouter sa valeur ASCII aux caractères de début de chaîne // EVO_84: found how to manage >16 characters : modulo 8 for (int pos = 0; pos < overFlow.Length; pos++) { nameChars[pos % 8] = (char)(nameChars[pos % 8] + overFlow[pos]); } return(String2.CharArrayToString(nameChars)); }
/// <summary> /// Backups target file then replaces it by file to install /// </summary> /// <param name="targetFileName">File to replace</param> /// <param name="fileToInstall">New file</param> private static void _Replace(string targetFileName, string fileToInstall) { if (string.IsNullOrEmpty(fileToInstall) || string.IsNullOrEmpty(targetFileName)) { return; } try { // Does backup already exist ? string backupFileName = targetFileName + "." + EXTENSION_BACKUP; if (!File.Exists(backupFileName)) { throw new Exception(_ERROR_NOTHING_TO_UPDATE + ": " + targetFileName); } // Removing read-only attribute File2.RemoveAttribute(targetFileName, FileAttributes.ReadOnly); // Copy File.Copy(fileToInstall, targetFileName, true); } catch (Exception ex) { MessageBoxes.ShowWarning(_Instance, ex.Message); } }
private void bnkDeleteToolStripButton_Click(object sender, EventArgs e) { int fileCount = bnkListView.SelectedItems.Count; if (fileCount == 0) { return; } // Confirmation, when deleting multiple files. With a single file, using default Windows dialog. bool confirmationAsked = false; if (fileCount > 1) { string message = string.Format(_QUESTION_DELETE_FILES, fileCount); DialogResult dr = MessageBoxes.ShowQuestion(this, message, MessageBoxButtons.YesNo); if (dr != DialogResult.Yes) { return; } confirmationAsked = true; } try { bool deleteResult = false; Cursor = Cursors.WaitCursor; // Parcours de la liste de fichiers sélectionnés foreach (ListViewItem anotherItem in bnkListView.SelectedItems) { string fileName = CurrentFolder + @"\" + anotherItem.Text; // On enlève les attributs éventuels File.SetAttributes(fileName, FileAttributes.Normal); // On supprime if (File2.MoveToTrash(fileName, !confirmationAsked)) { deleteResult = true; } } // Mise à jour de la liste, si nécessaire if (deleteResult) { _RefreshFileList(folderTreeView.SelectedNode, true); } Cursor = Cursors.Default; } catch (Exception ex) { MessageBoxes.ShowError(this, ex); } }
/// <summary> /// Constructeur principal /// </summary> /// <param name="dbFileName">Nom du fichier de bases de données à charger</param> internal DBResource(string dbFileName) { _FileName = dbFileName; _CurrentCulture = (DB.Culture)Enum.Parse(typeof(DB.Culture), File2.GetExtensionFromFilename(_FileName).ToUpper()); // Lecture _ReadData(); }
/// <summary> /// Writes camera file back /// </summary> public override void Save() { // Removing read-only attribute if (File.Exists(_FileName)) { File2.RemoveAttribute(_FileName, FileAttributes.ReadOnly); } using (BinaryWriter writer = new BinaryWriter(new FileStream(_FileName, FileMode.Create, FileAccess.Write))) { // Header _WriteHeader(writer); // Camera index _WriteIndex(writer); // Browsing camera sets foreach (CamEntry anotherEntry in _entries) { if (anotherEntry.isValid) { // Views foreach (View anotherView in anotherEntry.views) { // Zero1 (4 bytes) writer.Write(0); // Unknown1 (180 bytes) writer.Write(anotherView.unknown1); // Tag (?) writer.Write(anotherView.tag); // Camera id writer.Write(anotherView.cameraId); // Zero2 (2 bytes) writer.Write((short)0); // View type writer.Write((short)anotherView.type); // Zero3 (2 bytes) writer.Write((short)0); // View name + custom properties writer.Write(_SetViewName(anotherView)); // Unknown2 (420 bytes) // Positions : 195>source, 211>target anotherView.unknown2[195] = (byte)anotherView.source; anotherView.unknown2[211] = (byte)anotherView.target; writer.Write(anotherView.unknown2); } } } } }
private void LoadBtn_Click(object sender, RoutedEventArgs e) { if (Global.DownloadFolder != "hitomi_downloaded") { new TaskFactory().StartNew(() => LoadHitomi(File2.GetDirectories(root: "", path, rootDir + Global.DownloadFolder))); } else { new TaskFactory().StartNew(() => LoadHitomi(path)); } }
private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { // Main window is closed > cleaning... try { File2.RemoveTemporaryFolder(null, LibraryConstants.FOLDER_TEMP); } catch (Exception) { Log.Info("Unable to remove temporary folder - does not matter."); } }
/// <summary> /// Met à jour les tailles des entrées spécifiées. /// Ecrit directement dans le fichier /// </summary> /// <param name="idList">liste d'identifiants internes de fichiers</param> /// <param name="size1List">liste des tailles 1 à appliquer</param> /// <param name="size2List">liste des tailles 2 à appliquer</param> public void UpdateEntrySizes(Collection <uint> idList, Collection <uint> size1List, Collection <uint> size2List) { if (idList == null || size1List == null || size2List == null) { return; } // Parcours des entrées for (int i = 0; i < idList.Count; i++) { uint fileId = idList[i]; uint size1 = size1List[i]; uint size2 = size2List[i]; // Récupération de l'entrée Entry e = EntryList[fileId]; // Mise à jour de la structure e.firstSize = size1; e.secondSize = size2; // Enregistrement dans le fichier BinaryWriter mapWriter = null; try { // ANO_22 : on enlève l'attribut 'lecture seule' sur le fichier File2.RemoveAttribute(FileName, FileAttributes.ReadOnly); mapWriter = new BinaryWriter(new FileStream(FileName, FileMode.Open)); mapWriter.BaseStream.Seek(e.address, SeekOrigin.Begin); // Taille 1 mapWriter.BaseStream.Seek(0x4, SeekOrigin.Current); mapWriter.Write(BinaryTools.ToLittleEndian(size1)); // Taille 2 mapWriter.BaseStream.Seek(0x4, SeekOrigin.Current); mapWriter.Write(BinaryTools.ToLittleEndian(size2)); // Mise à jour de la liste d'entrées EntryList.Remove(fileId); EntryList.Add(fileId, e); } finally { if (mapWriter != null) { mapWriter.Close(); } } } }
/// <summary> /// Reads file data. This method should not be called from subclasses ! /// </summary> protected override void _ReadData() { try { // File decryption string tempFolder = File2.SetTemporaryFolder(null, LibraryConstants.FOLDER_TEMP, true); _WorkingFileName = string.Concat(tempFolder, FILE_AICONFIG_XML); XTEAEncryption.Decrypt(_FileName, _WorkingFileName); // Extracting xml and dirty data byte[] xmlData; using (BinaryReader reader = new BinaryReader(new FileStream(_WorkingFileName, FileMode.Open, FileAccess.Read))) { // Finding 0x00 0x00 sequence byte readByte = 0xAA; while (readByte != 0x00) { readByte = reader.ReadByte(); } long xmlPartLength = reader.BaseStream.Position; reader.BaseStream.Seek(0, SeekOrigin.Begin); xmlData = reader.ReadBytes((int)(xmlPartLength - 1)); _DirtyData = reader.ReadBytes((int)(reader.BaseStream.Length - xmlData.Length)); } // Loading xml... _Doc = new XmlDocument(); File2.WriteBytesToFile(_WorkingFileName, xmlData); _Doc.Load(_WorkingFileName); // Locating zones const string xRequest = "/AICONFIG/VEHICLE_REPARTITION/ZONE"; _ZoneNodes = _Doc.SelectNodes(xRequest); if (_ZoneNodes == null || _ZoneNodes.Count == 0) { throw new Exception("Invalid zoning data in AIConfig.xml: see " + xRequest); } } catch (Exception ex) { throw new Exception("Unable to read file: " + _FileName, ex); } }
static async Task Main(string[] args) { Console.WriteLine("开始"); File[] cs = new File[2]; cs[0] = new File { Path = "path1" }; cs[1] = new File { Path = "path2" }; var file = new File(); file.Children = cs; var files = file.GetFiles(); foreach (var tfile in files) { Console.WriteLine(tfile.Path); } Console.WriteLine("结束"); File2[] cs2 = new File2[2]; cs2[0] = new File2 { Path = "path21" }; cs2[1] = new File2 { Path = "path22" }; var file2 = new File2(); file2.Children = cs2; var file2s = file2.GetFiles(); foreach (var tfile in file2s) { Console.WriteLine(tfile.Path); } //// dosomething //Console.WriteLine("方法一、当前线程ID:" + Thread.CurrentThread.ManagedThreadId); //await DoSomething(); //Console.WriteLine("方法二、当前线程ID:" + Thread.CurrentThread.ManagedThreadId); //// dosomething //Console.ReadLine(); }
/// <summary> /// Handles packed file renaming. Extensions can't be changed for now. /// BNK is automatically saved. /// </summary> /// <param name="renamedPackedFile"></param> /// <param name="newFileName"></param> private void _RenamePackedFile(PackedFile renamedPackedFile, string newFileName) { if (renamedPackedFile != null && !string.IsNullOrEmpty(newFileName)) { // Changing file info node should be sufficient... FileInfoNode infoNode = _FileInfoByPathList[renamedPackedFile.filePath]; infoNode.name = File2.GetNameFromFilename(newFileName); renamedPackedFile.fileName = newFileName; // Final saving Save(); } }
/// <summary> /// Réalise la conversion multiple /// </summary> private void _MultipleConvert() { // Vérifications if (string.IsNullOrEmpty(sourceBNKTextBox.Text) || string.IsNullOrEmpty(targetFolderTextBox.Text)) { return; } Cursor = Cursors.WaitCursor; // Parcours des fichiers et extraction des 2DB BNK bnkFile = TduFile.GetFile(sourceBNKTextBox.Text) as BNK; if (bnkFile == null) { throw new Exception(_ERROR_INVALID_BNK_FILE); } Collection <string> textureFiles = bnkFile.GetPackedFilesPathsByExtension(LibraryConstants.EXTENSION_2DB_FILE); string tempFolder = File2.SetTemporaryFolder(null, LibraryConstants.FOLDER_TEMP, true); foreach (string anotherFilePath in textureFiles) { // 1.Extraction depuis le BNK vers le dossier temporaire bnkFile.ExtractPackedFile(anotherFilePath, tempFolder, true); // 2.Conversion des fichiers 2DB>DDS string fileName = tempFolder + @"\" + bnkFile.GetPackedFileName(anotherFilePath); FileInfo fi = new FileInfo(fileName); string newFileName = targetFolderTextBox.Text + @"\" + File2.ChangeExtensionOfFilename(fi.Name, LibraryConstants.EXTENSION_DDS_FILE); // If file already exists, it is renamed Tools.RenameIfNecessary(newFileName, LibraryConstants.SUFFIX_OLD_FILE); GraphicsConverters._2DBToDDS(fileName, newFileName); } // EVO 32 string message = string.Format(_STATUS_SUCCESS_MULTIPLE, textureFiles.Count); StatusBarLogManager.ShowEvent(this, message); // On efface le champ source sourceBNKTextBox.Text = ""; // Mise à jour de l'emplacement des 2DB _2DBLocationLink.Text = tempFolder; Cursor = Cursors.Default; }
/// <summary> /// Changes name of specified packed file /// </summary> /// <param name="packedFilePath"></param> /// <param name="newPackedFileName"></param> public void RenamePackedFile(string packedFilePath, string newPackedFileName) { try { if (!string.IsNullOrEmpty(packedFilePath) && !string.IsNullOrEmpty(newPackedFileName)) { // Extension check string packedFileName = GetPackedFileName(packedFilePath); string oldExtension = File2.GetExtensionFromFilename(packedFileName); string newExtension = File2.GetExtensionFromFilename(newPackedFileName); if (oldExtension != null && newExtension != null && !oldExtension.Equals(newExtension, StringComparison.InvariantCultureIgnoreCase)) { throw new Exception(_ERROR_RENAMING_EXTENSIONS); } // Name check if (GetPackedFilesPaths(newPackedFileName).Count > 0) { throw new Exception(string.Format(_FORMAT_ERROR_PACKED_FILE_NAME_EXISTS, newPackedFileName)); } // Getting packed file... PackedFile packedFile = _GetPackedFile(packedFilePath); if (packedFile.exists) { _RenamePackedFile(packedFile, newPackedFileName); } else { throw new Exception(string.Format(_FORMAT_ERROR_PACKED_FILE_NOT_EXISTS, packedFilePath)); } } else { throw new Exception("Forbidden operation."); } } catch (Exception ex) { throw new Exception("Unable to rename packed file: " + packedFilePath + "\r\n" + ex.Message, ex); } }
/// <summary> /// Implémentation de l'édition /// </summary> public override void Edit() { if (!string.IsNullOrEmpty(FileName)) { // L'édition d'un fichier 2DB passe par une conversion en DDS string ddsFilename = File2.ChangeExtensionOfFilename(FileName, LibraryConstants.EXTENSION_DDS_FILE); // BUG_49: if DDS file already exists, then open it directly if (!File.Exists(ddsFilename)) { GraphicsConverters._2DBToDDS(FileName, ddsFilename); } // Lancement de l'éditeur par défaut __SystemRun(ddsFilename); } }
/// <summary> /// Runs this instance. /// </summary> /// <param name="PushToNuget">if set to <c>true</c> [push to nuget].</param> /// <returns>True if it runs successfully, false otherwise</returns> public bool Run(bool PushToNuget) { foreach (FileInfo File in new DirectoryInfo("..\\..\\..\\UtilitiesPackages\\").EnumerateFiles("*.nuspec", System.IO.SearchOption.AllDirectories)) { string FileContent = File.Read(); string CurrentVersion = Regex.Match(FileContent, "<version>(?<VersionNumber>.*)</version>").Groups["VersionNumber"].Value; string CurrentID = Regex.Match(FileContent, "<id>(?<ProjectID>.*)</id>").Groups["ProjectID"].Value; foreach (FileInfo File2 in new DirectoryInfo("..\\..\\..\\UtilitiesPackages\\").EnumerateFiles("*.nuspec", System.IO.SearchOption.AllDirectories).Where(x => (FileInfo)x != File)) { FileContent = File2.Read(); FileContent = Regex.Replace(FileContent, @"<dependency id=""" + CurrentID + @""" version=""(?<VersionNumber>[^""]*)"" />", x => @"<dependency id=""" + CurrentID + @""" version=""[" + CurrentVersion + @"]"" />"); File2.Write(FileContent); } } return(true); }
/// <summary> /// Writes current BNK file to disk. /// This method is not to be called directly in BNK context. /// </summary> public override void Save() { try { // Removing read-only flag File2.RemoveAttribute(_FileName, FileAttributes.ReadOnly); // Getting all data byte[] fileSizeData = _WriteSection(SectionType.FileSize); byte[] typeMappingData = new byte[0]; byte[] fileNameData = _WriteSection(SectionType.FileName); byte[] fileOrderData = _WriteSection(SectionType.FileOrder); byte[] fileData = _WriteSection(SectionType.FileData); if (_GetSection(SectionType.TypeMapping).isPresent) { typeMappingData = _WriteSection(SectionType.TypeMapping); } // Computing new section addresses _ComputeSectionAddresses(fileSizeData, typeMappingData, fileNameData, fileOrderData); // Warning ! Files address may have changed. fileSize section data may need to be updated (written again) fileSizeData = _WriteSection(SectionType.FileSize); // Header is written, finally byte[] headerData = _WriteSection(SectionType.Header); // Writing into file using (BinaryWriter newBnkWriter = new BinaryWriter(new FileStream(_FileName, FileMode.Create, FileAccess.Write))) { newBnkWriter.Write(headerData); newBnkWriter.Write(fileSizeData); newBnkWriter.Write(typeMappingData); newBnkWriter.Write(fileNameData); newBnkWriter.Write(fileOrderData); newBnkWriter.Write(fileData); } } catch (Exception ex) { throw new Exception("Error when saving BNK file: " + _FileName, ex); } }
/// <summary> /// Extrait le fichier spécifié du BNK. /// If destination file already exists, it is renamed to *_old. /// </summary> /// <param name="aFile">Fichier empaqueté</param> /// <param name="path">Nom du fichier à créer ou nom du dossier où il doit être extrait (le nom sera inchangé)</param> /// <param name="toFolder">true si le path désigne un nom de dossier, false si c'est un nom de fichier</param> private static void _ExtractPackedFile(PackedFile aFile, string path, bool toFolder) { if (!string.IsNullOrEmpty(path) && aFile.exists) { // Gestion des deux modes d'extraction string newFileName = path; if (toFolder) { newFileName = Path.Combine(path, aFile.fileName); } // Same name management Tools.RenameIfNecessary(newFileName, LibraryConstants.SUFFIX_OLD_FILE); // On lance la création File2.WriteBytesToFile(newFileName, aFile.Data); } }