public ArchiveFile ReadFile(string filepath, bool surpressErrors) { if (!_indexTable.ContainsKey(filepath)) { if (!surpressErrors) { throw new FileNotFoundException("File with given path was not found in the releasemanifest"); } Console.WriteLine("Following file was not found in the releasemanifest: {0}", filepath); return(null); } if (!_fileTable.ContainsKey(filepath)) { if (!surpressErrors) { throw new FileNotFoundException("File with given path was not found in the file table"); } Console.WriteLine("Following file was not found: {0}", filepath); return(null); } var archive = _fileTable[filepath][0]; var info = archive.Files[filepath]; var result = new ArchiveFile(); result.Data = _reader.ReadData(archive, info.DataOffset, info.DataLength); result.CompressedSize = _indexTable[filepath].CompressedSize; result.UncompressedSize = _indexTable[filepath].DecompressedSize; return(result); }
private void OnExtractFileSelected(ArchiveFile archive, string fileName) { // User needs to choose where to save the extracted file FileBrowser.SetFilters(false, Path.GetExtension(fileName)); FileBrowser.ShowSaveDialog((string path) => OnExtractFileSavePathSelected(archive, fileName, path), () => OnExtractFileCanceled(archive), false, UserPrefs.gameDirectory, "Destination File Path", "Extract"); }
private void AddToListOfFiles(ArchiveFile extractFile) { if (!_fileNames.Any(file => file.Equals(extractFile.Name))) { _fileNames.Add(extractFile.Name); } }
/// <summary> /// Method to get all embedded files as list according to the target image / file (format) type /// </summary> /// <param name="archive">Reference to the opened file (handled as archive)</param> /// <returns>A list of items</returns> private List <ExtractorItem> GetEntries(ref ArchiveFile archive) { List <ExtractorItem> list = new List <ExtractorItem>(); MemoryStream ms; string[] split; char[] delimiter = new char[] { '\\', '/' }; string file, path; ExtractorItem item; for (int i = 0; i < archive.Entries.Count; i++) { if (archive.Entries[i].IsFolder) { continue; // Skip folders as entries } ms = new MemoryStream(); archive.Entries[i].Extract(ms); ms.Flush(); ms.Position = 0; split = archive.Entries[i].FileName.Split(delimiter); file = split[split.Length - 1]; path = archive.Entries[i].FileName.Substring(0, archive.Entries[i].FileName.Length - file.Length); item = new ExtractorItem(file, ms, path, currentModel.GenericTextPreview); item.Crc32 = archive.Entries[i].CRC; item.FileSize = (long)archive.Entries[i].Size; item.LastChange = archive.Entries[i].LastWriteTime; list.Add(item); } return(list); }
/// <summary> /// Method to extract an embedded file /// </summary> public void Extract() { try { FileInfo fi = new FileInfo(FileName); MemoryStream ms = GetFileStream(); ArchiveFile ex = ArchiveResolver.Open(ms, fi.Extension.ToLower().TrimStart('.')); embeddedFiles = GetEntries(ref ex); currentModel.NumberOfFiles = embeddedFiles.Count; for (int i = 0; i < currentModel.NumberOfFiles; i++) { switch (embeddedFiles[i].ItemType) { case ExtractorItem.Type.Image: embeddedFiles[i].CreateImage(); break; case ExtractorItem.Type.Xml: embeddedFiles[i].CreateXml(); break; case ExtractorItem.Type.Text: embeddedFiles[i].CreateText(); break; } currentModel.CurrentFile = i + 1; } } catch (Exception e) { hasErrors = true; lastError = e.Message; } }
/// <summary> /// This will assign all files to the proper destination. /// </summary> /// <param name="fileList">The list of files inside the mod archive.</param> /// <param name="stopPatterns">patterns matching files or directories that should be at the top of the directory structure.</param> /// <param name="progressDelegate">A delegate to provide progress feedback.</param> /// <param name="coreDelegate">A delegate for all the interactions with the js core.</param> protected async Task <List <Instruction> > BasicModInstall(List <string> fileList, List <string> stopPatterns, ProgressDelegate progressDelegate, CoreDelegates coreDelegate) { List <Instruction> FilesToInstall = new List <Instruction>(); string prefix = ArchiveStructure.FindPathPrefix(fileList, stopPatterns); await Task.Run(() => { foreach (string ArchiveFile in fileList) { if (ArchiveFile.EndsWith("" + Path.DirectorySeparatorChar)) { // don't include directories, only files continue; } string destination; if (ArchiveFile.StartsWith(prefix)) { destination = ArchiveFile.Substring(prefix.Length); } else { destination = ArchiveFile; } FilesToInstall.Add(Instruction.CreateCopy(ArchiveFile, destination)); // Progress should increase. } }); return(FilesToInstall); }
public void ReadArchiveFile() { archiveFile = new ArchiveFile { Signature = archiveFileReader.ReadFourCC(), Version = archiveFileReader.ReadUInt32(), }; archiveFileReader.Skip(512); archiveFile.FileSize = archiveFileReader.ReadUInt32(); archiveFileReader.Skip(12); archiveFile.FileDataInfoOffset = archiveFileReader.ReadUInt64(); archiveFile.FileDataInfoCount = archiveFileReader.ReadUInt64() - 3; // Set to AARC start. archiveFileReader.BaseStream.Position = 0x270 + 8; var fileCount = archiveFileReader.ReadUInt32(); archiveFileReader.BaseStream.Position = (long)archiveFile.FileDataInfoOffset + 32; var position = archiveFileReader.BaseStream.Position; archiveFileReader.BaseStream.Position = archiveFileReader.ReadInt64(); archiveFile.FileDataInfo = new List <FileDataInfoEntry>((int)archiveFile.FileDataInfoCount); for (var i = 0u; i < archiveFile.FileDataInfoCount; i++) { var fdie = new FileDataInfoEntry { Index = archiveFileReader.ReadUInt32(), Hash = archiveFileReader.ReadBytes(20), Size = archiveFileReader.ReadUInt64() }; archiveFile.FileDataInfo.Add(fdie); } archiveFileReader.BaseStream.Position = position + 16; var offsetMapStart = archiveFileReader.BaseStream.Position; for (var i = 0; i < (long)archiveFile.FileDataInfoCount; i++) { FileEntry entry; if (files.TryGetValue(archiveFile.FileDataInfo[i].Hash, out entry)) { archiveFileReader.BaseStream.Position = offsetMapStart + archiveFile.FileDataInfo[i].Index * 16 - 0x30; files[archiveFile.FileDataInfo[i].Hash].ArchiveOffset = archiveFileReader.ReadUInt64(); archiveFileReader.Skip(8); } } }
public void OnNavigatedTo(NavigationContext context) { try { _archiveType = (ArchiveType)context.Parameters["archiveType"]; _archiveFileName = (string)context.Parameters["archiveFileName"]; _testSession = Directory.Exists(_archiveFileName) ? _arkadeApi.CreateTestSession(ArchiveDirectory.Read(_archiveFileName, _archiveType)) : _arkadeApi.CreateTestSession(ArchiveFile.Read(_archiveFileName, _archiveType)); if (!_testSession.IsTestableArchive()) { _statusEventHandler.RaiseEventOperationMessage( Resources.GUI.TestrunnerArchiveTestability, string.Format(Resources.GUI.TestrunnerArchiveNotTestable, ArkadeProcessingArea.LogsDirectory), OperationMessageStatus.Warning ); } StartTestingCommand.RaiseCanExecuteChanged(); // testSession has been updated, reevaluate command } catch (Exception e) { string message = string.Format(Resources.GUI.ErrorReadingArchive, e.Message); Log.Error(e, message); _statusEventHandler.RaiseEventOperationMessage(null, message, OperationMessageStatus.Error); } }
private void GenerateSourcesForProject(CompilerInvocation invocation, string outputDirectory) { var virtualProjectDirectory = invocation.ProjectDirectory; virtualProjectDirectory = ArchiveFile.CalculateArchivePath(virtualProjectDirectory); var physicalProjectPath = GetPhysicalPath(outputDirectory, virtualProjectDirectory); }
private void GenerateSourcesForProject(CompilerInvocation invocation, string outputDirectory) { var virtualProjectFilePath = invocation.ProjectFilePath; virtualProjectFilePath = ArchiveFile.CalculateArchivePath(virtualProjectFilePath); var physicalProjectPath = GetPhysicalPath(outputDirectory, virtualProjectFilePath); var physicalProjectDirectory = Path.GetDirectoryName(physicalProjectPath); if (!Directory.Exists(physicalProjectDirectory)) { return; } var arguments = invocation.CommandLineArguments.Tokenize(); foreach (var argument in arguments) { if (argument.StartsWith("/")) { var reference = TryGetReference(argument); if (reference != null) { reference = ArchiveFile.CalculateArchivePath(reference); var physicalReferencePath = GetPhysicalPath(outputDirectory, reference); WriteEmptyAssembly(physicalReferencePath); } } else { var sourceRelativePath = argument.TrimQuotes(); var physicalSourcePath = Path.Combine(physicalProjectDirectory, sourceRelativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); physicalSourcePath = Path.GetFullPath(physicalSourcePath); WriteFile(physicalSourcePath, ""); } } }
public void Execute(ArchiveFile archive) { var usa = GetSubset(archive.Entries, rom => rom.FileName.Contains("(U)") || rom.FileName.Contains("(JU)") || rom.FileName.Contains("(W)")); var japan = GetSubset(archive.Entries, "(J)"); var europe = GetSubset(archive.Entries, "(E)"); //var hack = GetSubset(archive.Entries, "Hack)"); bool isUsa, isJapan, isEurope; //SortUnlicensed(hack, "Hacks"); isUsa = Sort(usa, Util.Folder.AllOfficialReleases); if (isUsa) { return; } isEurope = Sort(europe, Util.Folder.AllOfficialReleases); if (isEurope) { return; } isJapan = Sort(japan, Util.Folder.AllOfficialReleases); if (isJapan) { return; } //if (hack.Count() == 0) // SortUnlicensed(archive.Entries, "Unknown"); }
static void Main(string[] args) { using (ArchiveFile archiveFile = new ArchiveFile(@"Archive.arj")) { // extract all archiveFile.Extract("Output"); } using (ArchiveFile archiveFile = new ArchiveFile("archive.arj")) { foreach (Entry entry in archiveFile.Entries) { Console.WriteLine(entry.FileName); // extract to file entry.Extract(entry.FileName); // extract to stream MemoryStream memoryStream = new MemoryStream(); entry.Extract(memoryStream); } } Console.WriteLine(""); Console.WriteLine("done"); Console.ReadKey(); }
/// <summary> /// Method to try opening an archive without defined format /// </summary> /// <param name="stream">Memory stream of the archive</param> /// <param name="archive">Opened archive as out parameter. May be null in case of an error</param> /// <param name="error">Error message. May be empty, if no error occurred</param> /// <returns>True if the extraction was successful, otherwise false</returns> private static bool TryOpen(ref MemoryStream stream, out ArchiveFile archive, out string error) { ArchiveFile arch; string err; if (OpenArchive(ref stream, SevenZipFormat.Zip, out arch, out err)) { archive = arch; error = string.Empty; return(true); } foreach (KeyValuePair <string, SevenZipFormat> format in ArchiveFormats) { if (format.Value == SevenZipFormat.Zip) { continue; // Already checked } if (OpenArchive(ref stream, format.Value, out arch, out err)) { archive = arch; error = string.Empty; return(true); } } error = err; archive = null; return(false); }
private ArchiveViewResult(ZipFile archive, ArchiveFile file, FileSystemModel model) { IsValid = true; Archive = archive; File = file; Model = model; }
public void TestReadSpeed() { Console.WriteLine("Opening archive file..."); using (ArchiveFile file = OpenArchiveFile("c:\\temp\\benchmark\\test_archive.d")) { file.DataWriteException += (sender, e) => Console.WriteLine("Data Read Exception: {0}", e.Argument.Message); Console.WriteLine("Start file read..."); long pointCount = 0; Stopwatch sw = new Stopwatch(); sw.Start(); foreach (IDataPoint dataPoint in file.ReadData(Enumerable.Range(1, MetaDataPoints), TimeTag.MinValue, TimeTag.MaxValue)) { //if (dataPoint.Value != 0.0F) // throw new Exception("Corrupt"); pointCount++; } double totalTime = sw.Elapsed.TotalSeconds; Console.WriteLine("Completed read test in {0:#,##0.00} seconds at {1:#,##0.00} points per second", totalTime, pointCount / totalTime); Console.WriteLine("Read points = {0:#,##0}", pointCount); } }
public static string CreateProject(string dir, ArchiveFile template) { System.IO.Directory.CreateDirectory(dir); template.Extract(dir); return System.IO.Path.Combine(dir, "Game.nkproj"); }
/// <summary> /// クラウド側でコピーを行う。 /// </summary> /// <param name="sourceFile">コピー元ファイル</param> /// <param name="destinationBlob">コピー先Blob</param> /// <param name="destinationFile">コピー先ファイル</param> /// <returns>成功:true 失敗:false</returns> public bool CopyOnServer(ArchiveFile sourceFile, Blob destinationBlob, ArchiveFile destinationFile) { CloudBlockBlob destinationBlockBlob = destinationBlob.ArchiveFileToBlob(destinationFile); CloudBlockBlob sourceBlockBlob = ArchiveFileToBlob(sourceFile); bool result = false; // 本来ならStartCopyAsync等の、ローカルへのDownloadを介さない処理を使いたいが, // StartCopyAsyncはストレージアカウントを跨ぐ場合、URIを参照するため、 // コピー元がpublic Accessでないと失敗する。 _polly.Execute( () => { var destContainer = destinationBlob.GetContainerReadOnly(destinationFile.ContainerName); destContainer.CreateIfNotExistsAsync().Wait(); // MSサポートに問い合わせたところ、 // StartCopyAsyncをWaitすることで完了まで待機してもらえるということなので、その前提で実装する。 destinationBlockBlob.StartCopyAsync(sourceBlockBlob).Wait(); _logger.Debug($"Copy result [{destinationBlockBlob.CopyState}] from [{sourceFile.ContainerName}/{sourceFile.FilePath}] to [{destinationFile.ContainerName}/{destinationFile.FilePath}] "); if (destinationBlockBlob.CopyState != null && destinationBlockBlob.CopyState.Status == CopyStatus.Success) { result = true; } }); return(result); }
private void ExtractDATA() { O_TextBox.AppendText(Environment.NewLine + ""); if (File.Exists(EDir + @"\data.tar")) { O_TextBox.AppendText(Environment.NewLine + "Unpacking 'data.tar'..."); using (ArchiveFile tardataFile = new ArchiveFile(@"C:\E_temp\data.tar")) { tardataFile.Extract(EDir); } } else if (File.Exists(EDir + @"\data.tar.gz")) { O_TextBox.AppendText(Environment.NewLine + "File is 'data.tar.gz'! Rerunning method..."); O_TextBox.AppendText(Environment.NewLine + "Unpacking 'data.tar'..."); var processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = Application.StartupPath + @"\7Z\7z.exe"; processStartInfo.Arguments = @"e C:\E_temp\data.tar.gz"; var proc = Process.Start(processStartInfo); proc.WaitForExit(); File.Copy(@"data.tar", @"C:\E_temp\data.tar"); File.Delete(@"data.tar"); O_TextBox.AppendText(Environment.NewLine + "Method ran successfully! Unpacking 'data.tar'..."); using (ArchiveFile tar2dataFile = new ArchiveFile(@"C:\E_temp\data.tar")) { tar2dataFile.Extract(EDir); } } O_TextBox.AppendText(Environment.NewLine + "Unpacked 'data.tar'!"); }
private void PopulateFilesTab() { var root = new Folder(); foreach (var file in archiveFile.Files.OrderBy(kvp => kvp.Key, StringComparer.OrdinalIgnoreCase)) { AddSourceFile(root, file.Key); } foreach (var taskAssembly in Build.TaskAssemblies) { var filePath = ArchiveFile.CalculateArchivePath(taskAssembly.Key); var sourceFile = AddSourceFile(root, filePath); foreach (var taskName in taskAssembly.Value.OrderBy(s => s)) { var task = new Task { Name = taskName }; sourceFile.AddChild(task); } } foreach (var subFolder in root.Children.OfType <Folder>()) { CompressTree(subFolder); } filesTree.Items = root.Children; filesTree.GotFocus += (s, a) => ActiveTreeView = filesTree; filesTree.ContextMenu = sharedTreeContextMenu; }
/// <summary> /// Open an SDS from the FileInfo given. /// </summary> /// <param name="file">info of SDS.</param> private void OpenSDS(FileInfo file) { //backup file before unpacking.. if (!Directory.Exists(file.Directory.FullName + "/BackupSDS")) { Directory.CreateDirectory(file.Directory.FullName + "/BackupSDS"); } //place copy in new folder. string time = string.Format("{0}_{1}_{2}_{3}_{4}", DateTime.Now.TimeOfDay.Hours, DateTime.Now.TimeOfDay.Minutes, DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year); string filename = ToolkitSettings.AddTimeDataBackup == true?file.Name.Insert(file.Name.Length - 4, "_" + time) : file.Name; File.Copy(file.FullName, file.Directory.FullName + "/BackupSDS/" + filename, true); Log.WriteLine("Opening SDS: " + file.Name); fileListView.Items.Clear(); ArchiveFile archiveFile; using (var input = File.OpenRead(file.FullName)) { using (Stream data = ArchiveEncryption.Unwrap(input)) { archiveFile = new ArchiveFile(); archiveFile.Deserialize(data ?? input); } } Log.WriteLine("Succesfully unwrapped compressed data"); archiveFile.SaveResources(file); OpenDirectory(new DirectoryInfo(file.Directory.FullName + "/extracted/" + file.Name)); infoText.Text = "Opened SDS.."; }
public void ExtractAll() { using (ArchiveFile archiveFile = new ArchiveFile(ArchiveFileName)) { archiveFile.Extract(extractTo, true); } }
/// <summary> /// Failureストレージに再送用メッセージをアップロードする /// </summary> /// <param name="message">メッセージ</param> public void UpdateToFailureStorage(string message) { try { _logger.EnterJson("{0}", new { message }); DateTime now = _timeProvider.UtcNow; // ファイル情報 ArchiveFile file = new ArchiveFile() { ContainerName = _settings.FailureBlobContainerName, CreatedAt = now }; file.FilePath = string.Format(Utility.Const.FailureBlobFilenameFormat, now); // アップロード _failureRepository.Upload(file, message); } catch (RmsException e) { // Blobストレージへの保存処理に失敗した場合、メッセージ内容をログに出力して終了する。 _logger.Error(e, nameof(Resources.OP_MLS_MLS_004), new object[] { message }); } finally { _logger.Leave(); } }
/// <summary> /// Pack an SDS from the FileInfo given. /// </summary> /// <param name="file">location of SDS.</param> private void PackSDS(FileInfo file) { if (file == null) { MessageBox.Show("File is null"); } //begin.. infoText.Text = "Saving SDS.."; ArchiveFile archiveFile = new ArchiveFile { Platform = Platform.PC, Unknown20 = new byte[16] { 55, 51, 57, 55, 57, 43, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; archiveFile.BuildResources(file.Directory.FullName + "/extracted/" + file.Name); foreach (ResourceEntry entry in archiveFile.ResourceEntries) { if (entry.Data == null) { throw new FormatException(); } } using (var output = File.Create(file.FullName)) { archiveFile.Serialize(output, ToolkitSettings.SerializeSDSOption == 0 ? ArchiveSerializeOptions.OneBlock : ArchiveSerializeOptions.Compress); } infoText.Text = "Saved SDS."; }
public void ExtractAndIdentifyTarFiles() { var uuid = Uuid.Of("c3db9d4e-720c-4f75-bfb6-de90231dc44c"); string pathToExtractedFilesRegex = ArkadeProcessingArea.WorkDirectory.FullName + Path.DirectorySeparatorChar + "..............-" + uuid + Path.DirectorySeparatorChar + uuid; pathToExtractedFilesRegex = pathToExtractedFilesRegex.Replace("\\", "\\\\"); var extractorMock = new Mock <ICompressionUtility>(); extractorMock.Setup(e => e.ExtractFolderFromArchive(It.IsAny <FileInfo>(), It.IsAny <DirectoryInfo>())); var archiveType = ArchiveType.Noark5; var identifierMock = new Mock <IArchiveIdentifier>(); identifierMock.Setup(i => i.Identify(It.IsAny <string>())).Returns(archiveType); var statusEventHandler = new StatusEventHandler(); string file = TestUtil.TestDataDirectory + Path.DirectorySeparatorChar + "tar" + Path.DirectorySeparatorChar + "Noark3-eksempel-1" + Path.DirectorySeparatorChar + uuid + ".tar"; TestSession testSession = new TestSessionFactory(extractorMock.Object, statusEventHandler) .NewSession(ArchiveFile.Read(file, archiveType)); var archive = testSession.Archive; archive.Should().NotBeNull(); archive.Uuid.Should().Be(uuid); archive.WorkingDirectory.Root().DirectoryInfo().FullName.Should().MatchRegex(pathToExtractedFilesRegex); archive.ArchiveType.Should().Be(archiveType); System.IO.Directory.Delete(archive.WorkingDirectory.Root().DirectoryInfo().FullName, true); }
public static string unZipFile(string ArchiveFilePath, string Desnation, string FileName, string FileExt) { string ExtractedFileName = ""; using (ArchiveFile archiveFile = new ArchiveFile(ArchiveFilePath)) { foreach (Entry entry in archiveFile.Entries) { if (FileExt == ".gz") { Desnation = Desnation + FileName; ExtractedFileName = FileName; } else { Desnation = Desnation + entry.FileName.ToString(); ExtractedFileName = entry.FileName.ToString(); } if (File.Exists(Desnation)) { File.Delete(Desnation); } MemoryStream memoryStream = new MemoryStream(); using (FileStream file = new FileStream(Desnation, FileMode.Create, FileAccess.Write)) { entry.Extract(file); } } } return(ExtractedFileName); }
private string GetDestinationFileName(string sourceFileName, string instanceName, string destinationPath, ArchiveDirectoryMethod method) { using (ArchiveFile file = OpenArchiveFile(sourceFileName, ref instanceName)) { return(GetDestinationFileName(file, sourceFileName, instanceName, destinationPath, method)); } }
public void Onepass() { // 準備 var diBuilder = new TestDiProviderBuilder(); diBuilder.AddConfigure("BlobCleanTarget_container_filepath", "30"); // init // DBにファイルパス、データを追加 // コンテナがなければ作成 // Blobにそれと同じファイルを追加 var file = new ArchiveFile() { ContainerName = "", FilePath = "" }; // プロバイダ生成 var provider = diBuilder.Build(); // ■テストの本筋 var actual = provider.GetService <CleanBlobService>(); actual.Clean(); // 削除対象がGetできばOK // 非削除対象がGetできなければNG // 後始末 }
private void DeleteAction(object sender, EventArgs args) { DialogResult result = MessageBox.Show($"Are your sure you want to remove {Text}? This cannot be undone!", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { bool isRemoved = ArchiveFile.DeleteFile(ArchiveFileInfo); if (!isRemoved) { return; } if (Parent != null) { Parent.Nodes.Remove(this); } else if (ArchiveFileInfo.FileFormat != null && ArchiveFileInfo.FileFormat is TreeNode) { var prevNode = (TreeNode)ArchiveFileInfo.FileFormat; var parent = prevNode.Parent; var index = parent.Nodes.IndexOf(prevNode); parent.Nodes.RemoveAt(index); } } }
public void Initialise(string patchPath) { log.Info("Loading archives..."); // CoreData archive only applicable to Steam client ArchiveFile coreDataArchive = null; if (File.Exists(Path.Combine(patchPath, "CoreData.archive"))) { coreDataArchive = ArchiveFileBase.FromFile(Path.Combine(patchPath, "CoreData.archive")) as ArchiveFile; } MainArchive = Archive.FromFile(Path.Combine(patchPath, "ClientData.index"), coreDataArchive); foreach (string localisationArchivePath in localisationIndexes .Select(i => Path.Combine(patchPath, i))) { if (!File.Exists(localisationArchivePath)) { continue; } LocalisationArchives.Add(Archive.FromFile(localisationArchivePath, coreDataArchive)); } }
/// <summary> /// DtDeviceFileにレコードを追加する。 /// </summary> /// <param name="collectFile">CollectingBlob上の収集ファイル</param> /// <param name="fileOnPrimaryBlob">PrimaryBlob上の収集ファイル</param> /// <returns>true: 成功 false: 失敗</returns> private bool TryAddDtDeviceFile(CollectedFile collectFile, ArchiveFile fileOnPrimaryBlob) { try { // DBにファイル情報を保存する(ファイルURL、メタデータ) // まずsys_ownerから、端末情報を取得する。 // ・この値は機器UIDかエッジIDを使用する。 var device = _dtDeviceRepository.ReadDtDevice(collectFile.Owner); if (device == null) { throw new Exception(string.Format("Device[{0}]が見つかりませんでした。", collectFile.Owner)); } // 端末ファイルデータを作る var dtDeviceFile = new Utility.Models.Entites.DtDeviceFile() { DeviceSid = device.Sid, //// DB上は発生元機器UIDだが、端末のUIDとは限らないので、ここではOwnerの値を設定する。 SourceEquipmentUid = collectFile.Owner, Container = fileOnPrimaryBlob.ContainerName, FilePath = fileOnPrimaryBlob.FilePath, CollectDatetime = collectFile.CreatedAt, DtDeviceFileAttribute = fileOnPrimaryBlob.MetaData.Select(ToDtDeviceFileAttribute).ToArray() }; _dtDeviceFileRepository.CreateOrUpdateDtDeviceFile(dtDeviceFile); return(true); } catch (Exception ex) { _logger.Error(ex, nameof(Resources.CO_BLI_BLI_007), new object[] { fileOnPrimaryBlob.ContainerName, fileOnPrimaryBlob.FilePath }); return(false); } }
public void extractIPA(string path) { clean(); log("Extracting IPA " + path); try { using (ArchiveFile archiveFile = new ArchiveFile(path)) { if (verbose) { log("Extracting payload"); } archiveFile.Extract("temp"); } createDirIfDoesntExist("files\\Applications"); foreach (string app in Directory.GetDirectories("temp\\Payload\\")) { if (verbose) { log("Moving payload"); } Directory.Move(app, "files\\Applications\\" + new DirectoryInfo(app).Name); if (verbose) { log("Moved payload"); } } } catch (Exception e) { log("Not a valid IPA / Access Denied"); throw e; } }
void ReadDirSet(ArchiveFile af, Stream strm) { BinaryReader rd = new BinaryReader(strm); strm.Seek(af.Header.DirSetOffset, SeekOrigin.Begin); af.DirectorySet = new DirSet(); af.DirectorySet.Count = rd.ReadUInt32(); af.DirectorySet.Offsets = new uint[af.DirectorySet.Count]; af.DirectorySet.Entries = new DirSetEntry[af.DirectorySet.Count]; // read the offsets for (uint i = 0; i < af.DirectorySet.Count; i++) { af.DirectorySet.Offsets[i] = rd.ReadUInt32(); } for (uint i = 0; i < af.DirectorySet.Count; i++) { short strlen; byte[] strbuf; strm.Seek(af.Header.DirSetOffset + af.DirectorySet.Offsets[i], SeekOrigin.Begin); af.DirectorySet.Entries[i] = new DirSetEntry(); af.DirectorySet.Entries[i].ParentOffset = rd.ReadUInt32(); af.DirectorySet.Entries[i].ChildCount = rd.ReadUInt32(); af.DirectorySet.Entries[i].FileTime = DateTime.FromFileTime(rd.ReadInt64()); strlen = rd.ReadInt16(); strlen++; // add 0-byte at the end while ((2 + strlen) % 4 != 0) // pad to dword size strlen++; strbuf = new byte[strlen]; rd.Read(strbuf, 0, strlen); string name = Encoding.ASCII.GetString(strbuf); if (name.IndexOf('\0') >= 0) name = name.Substring(0, name.IndexOf('\0')); af.DirectorySet.Entries[i].Name = name; af.DirectorySet.Entries[i].ChildOffsets = new uint[af.DirectorySet.Entries[i].ChildCount]; for (int j = 0; j < af.DirectorySet.Entries[i].ChildCount; j++) { af.DirectorySet.Entries[i].ChildOffsets[j] = rd.ReadUInt32(); } // add to lookup table af.DirOffsets.Add(af.DirectorySet.Offsets[i], af.DirectorySet.Entries[i]); } af.DirectorySet.EndOffset = (uint)strm.Position; }
private async Task<MemoryStream> getExcel() { try { var url = Settings.Default.DbUrl; var path = Path.Combine(Environment.CurrentDirectory, "temp"); var file = Path.GetFileName(url); var filename = Path.Combine(path, file); if (!Directory.Exists(path)) Directory.CreateDirectory(path); var wc = new WebClient(); log("下载..."); wc.DownloadProgressChanged += (s, e) => Percent = e.ProgressPercentage; await wc.DownloadFileTaskAsync(new Uri(url), filename); logLine("完成"); log("解压..."); var ms = new MemoryStream(); using (var zip = new ArchiveFile(filename, "7z-x86.dll")) { foreach (var item in zip.Entries) if (item.FileName.EndsWith(".xls")) { item.Extract(ms); break; } } return ms; } catch (Exception ex) { logLine(ex.Message); return null; } }
public CreateProjectWizard() { InitializeComponent(); string[] filelist = StorageManager.GetVirtualDirectoryFiles("Templates", "*.nkar", System.IO.SearchOption.AllDirectories); this.templateList.LargeImageList = new ImageList(); this.templateList.LargeImageList.ColorDepth = ColorDepth.Depth32Bit; this.templateList.LargeImageList.ImageSize = new Size(48, 48); this.templateList.SmallImageList = new ImageList(); this.templateList.SmallImageList.ColorDepth = ColorDepth.Depth32Bit; this.templateList.SmallImageList.ImageSize = new Size(16, 16); this.templateList.Columns.Add("名称"); this.templateList.Columns.Add("版本"); this.templateList.Columns.Add("语言"); this.templateList.Columns.Add("备注"); this.templateList.View = View.Details; this.templateList.MultiSelect = false; this.templateList.FullRowSelect = true; this.templateList.HideSelection = false; this.templateList.Sorting = SortOrder.Ascending; foreach (string filename in filelist) { try { ArchiveFile file = new ArchiveFile(filename); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(file.Manifest); XmlNode root = xmldoc["NekoKunProjectTemplate"]; if (new Version(root.Attributes["Version"].Value) > new Version(((System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Reflection.AssemblyFileVersionAttribute), false)[0] as System.Reflection.AssemblyFileVersionAttribute).Version))) throw new ArgumentException("The project template file was created in a newer version of NekoKun which is not supported by this version of NekoKun."); ListViewItem lvi = new ListViewItem(); lvi.Tag = file; lvi.Text = root["Title"].InnerText; lvi.SubItems.Add(root["Version"] != null ? root["Version"].InnerText : ""); lvi.SubItems.Add(root["Language"] != null ? root["Language"].InnerText : ""); lvi.SubItems.Add(root["Description"] != null ? root["Description"].InnerText : ""); lvi.ToolTipText = root["Description"] != null ? root["Description"].InnerText : ""; if (root["Icon"] != null) { Image image = NekoKun.Core.DrawingHelper.DecodeBase64Image(root["Icon"].InnerText); this.templateList.LargeImageList.Images.Add(filename, image); this.templateList.SmallImageList.Images.Add(filename, image); lvi.ImageKey = filename; } this.templateList.Items.Add(lvi); } catch { } } if (this.templateList.Items.Count >= 1) this.templateList.Items[0].Selected = true; this.templateList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); FillFields(); this.fieldName.TextChanged += new EventHandler(fieldName_TextChanged); this.browseFolderButton.Click += new EventHandler(browseFolderButton_Click); UpdateAccept(); this.templateList.ItemSelectionChanged += delegate { UpdateAccept(); }; this.fieldLocation.TextChanged += delegate { UpdateAccept(); }; this.fieldName.TextChanged += delegate { UpdateAccept(); }; this.accpetButton.Click += new EventHandler(accpetButton_Click); }
private string GetRelPath(ArchiveFile af, FileSetEntry fse) { string res = fse.Name; uint ParentOffset = fse.ParentOffset; while (ParentOffset != 0) { DirSetEntry dse = af.DirOffsets[ParentOffset]; if (dse.ParentOffset == 0) break; res = String.Format("{0}/{1}", dse.Name, res); ParentOffset = dse.ParentOffset; } return res; }
private IntPtr OutputFileOpen(NativeMethods.FdiNotification fdin) { var extractFile = new ArchiveFile { Name = GetFileName(fdin) }; if (ShouldIgnoreFile(extractFile)) { //ignore this file. return IntPtr.Zero; } var stream = new MemoryStream(); GCHandle gch = GCHandle.Alloc(stream); extractFile.Handle = (IntPtr)gch; AddToListOfFiles(extractFile); //return IntPtr.Zero so that the iteration will keep on going return IntPtr.Zero; }
public override void AbstractOpen() { DirectoriesList.Clear(); FilesList.Clear(); var arc = ZipFile.Open(AbstractPath, ZipArchiveMode.Update); var existingFolders = new List<string>(); foreach (var item in arc.Entries) { if (item.FullName.LastIndexOf(@"/", System.StringComparison.Ordinal) == item.FullName.Length - 1) { if (InnerPath == "") { if ( existingFolders.Contains(item.FullName.Substring(0, item.FullName.IndexOf(@"/", System.StringComparison.Ordinal) + 1)) || item.FullName.Substring(0, item.FullName.IndexOf(@"/", System.StringComparison.Ordinal) + 1) == "") continue; var newFolder = new ArchiveFolder(AbstractPath, item.FullName.Substring(0, item.FullName.IndexOf(@"/", System.StringComparison.Ordinal) + 1)); DirectoriesList.Add(newFolder); existingFolders.Add(item.FullName.Substring(0, item.FullName.IndexOf(@"/", System.StringComparison.Ordinal) + 1)); } else { if (item.FullName.IndexOf(InnerPath, System.StringComparison.Ordinal) >= 0) { var inPath = item.FullName.Replace(InnerPath, ""); if (!existingFolders.Contains(inPath.Substring(0, inPath.IndexOf(@"/", System.StringComparison.Ordinal) + 1)) && inPath.Substring(0, inPath.IndexOf(@"/", System.StringComparison.Ordinal) + 1) != "") { var newFolder = new ArchiveFolder(AbstractPath, item.FullName); DirectoriesList.Add(newFolder); existingFolders.Add(inPath.Substring(0, inPath.IndexOf(@"/", System.StringComparison.Ordinal) + 1)); } } } } else { if (InnerPath == "") { if (item.FullName.IndexOf(@"/", System.StringComparison.Ordinal) < 0) { var newFile = new ArchiveFile(item.FullName, item); FilesList.Add(newFile); } } else { if (item.FullName.IndexOf(InnerPath, System.StringComparison.Ordinal) >= 0) { var inPath = item.FullName.Replace(InnerPath, ""); if (inPath.IndexOf(@"/", System.StringComparison.Ordinal) < 0) { var newFile = new ArchiveFile(item.FullName, item); FilesList.Add(newFile); } } } } } }
private bool ShouldIgnoreFile(ArchiveFile extractFile) { var rootFolder = GetFileRootFolder(extractFile.Name); return _subDirectoryToIgnore.Any(dir => dir.Equals(rootFolder, StringComparison.InvariantCultureIgnoreCase)); }
private ArchiveFile ReadDirectory(Stream strm) { ArchiveFile af = new ArchiveFile(); af.Header = ReadGlobalHeader(strm); ReadDirSet(af, strm); ReadFileSet(af, strm); return af; }
private void ExtractFile(string fileName) { _currentFileToDecompress = new ArchiveFile { Name = fileName }; FdiCopy(); CreateAllRelevantDirectories(fileName); if (_currentFileToDecompress.Data != null) { File.WriteAllBytes(Path.Combine(_extractionFolderPath, _currentFileToDecompress.Name), _currentFileToDecompress.Data); } }
void ReadFileSet(ArchiveFile af, Stream strm) { BinaryReader rd = new BinaryReader(strm); strm.Seek(af.Header.FileSetOffset, SeekOrigin.Begin); af.FileSet = new FileSet(); af.FileSet.Count = rd.ReadUInt32(); af.FileSet.Offsets = new uint[af.FileSet.Count]; af.FileSet.Entries = new FileSetEntry[af.FileSet.Count]; for (int i = 0; i < af.FileSet.Count; i++) { af.FileSet.Offsets[i] = rd.ReadUInt32(); } for (int i = 0; i < af.FileSet.Count; i++) { short strlen; byte[] strbuf; strm.Seek(af.Header.FileSetOffset + af.FileSet.Offsets[i], SeekOrigin.Begin); af.FileSet.Entries[i] = new FileSetEntry(); af.FileSet.Entries[i].ParentOffset = rd.ReadUInt32(); af.FileSet.Entries[i].Size = rd.ReadUInt32(); af.FileSet.Entries[i].Offset = rd.ReadUInt32(); af.FileSet.Entries[i].CRC = rd.ReadUInt32(); af.FileSet.Entries[i].FileTime = DateTime.FromFileTime(rd.ReadInt64()); af.FileSet.Entries[i].Format = rd.ReadInt16(); af.FileSet.Entries[i].Flags = rd.ReadInt16(); strlen = rd.ReadInt16(); strlen++; // add 0-byte at the end while ((2 + strlen) % 4 != 0) // pad to dword size strlen++; strbuf = new byte[strlen]; rd.Read(strbuf, 0, strlen); string name = Encoding.ASCII.GetString(strbuf); if (name.IndexOf('\0') >= 0) name = name.Substring(0, name.IndexOf('\0')); af.FileSet.Entries[i].Name = name; if (af.FileSet.Entries[i].Format != 0) { // compressed resource; read compression header af.FileSet.Entries[i].CompressedSize = rd.ReadUInt32(); af.FileSet.Entries[i].ChunkSize = rd.ReadUInt32(); af.FileSet.Entries[i].NumChunks = (uint)Math.Ceiling((double)af.FileSet.Entries[i].Size / (double)af.FileSet.Entries[i].ChunkSize); af.FileSet.Entries[i].ChunkHeaders = new ChunkHeader[af.FileSet.Entries[i].NumChunks]; for (int j = 0; j < af.FileSet.Entries[i].NumChunks; j++) { af.FileSet.Entries[i].ChunkHeaders[j] = new ChunkHeader(); af.FileSet.Entries[i].ChunkHeaders[j].UncompressedSize = rd.ReadUInt32(); af.FileSet.Entries[i].ChunkHeaders[j].CompressedSize = rd.ReadUInt32(); af.FileSet.Entries[i].ChunkHeaders[j].ExtraBytes = rd.ReadUInt32(); af.FileSet.Entries[i].ChunkHeaders[j].Offset = rd.ReadUInt32(); } } // add to lookup table af.FileOffsets.Add(af.FileSet.Offsets[i], af.FileSet.Entries[i]); } }
public override AbstractFile AbstractCreateFile(string fileName) { using (var arc = ZipFile.Open(AbstractPath, ZipArchiveMode.Update)) { var newEntry = arc.CreateEntry(InnerPath + fileName); var newFile = new ArchiveFile(newEntry.FullName, newEntry); return newFile; } }