public MSCabCompression(Stream stream) { this.stream = stream; var signature = stream.ReadASCII(4); if (signature != "MSCF") throw new InvalidDataException("Not a Microsoft CAB package!"); stream.Position += 12; var filesOffset = stream.ReadUInt32(); stream.Position += 6; var folderCount = stream.ReadUInt16(); var fileCount = stream.ReadUInt16(); if (stream.ReadUInt16() != 0) throw new InvalidDataException("Only plain packages (without reserved header space or prev/next archives) are supported!"); stream.Position += 4; folders = new CabFolder[folderCount]; for (var i = 0; i < folderCount; i++) { folders[i] = new CabFolder(stream); if (folders[i].CompressionType != 1) throw new InvalidDataException("Compression type is not supported"); } files = new CabFile[fileCount]; stream.Seek(filesOffset, SeekOrigin.Begin); for (var i = 0; i < fileCount; i++) files[i] = new CabFile(stream); }
private int Do(IEnumerable <IFileArchivedBase> filesIn, Action action) { if (filesIn == null) { return(0); } var files = filesIn.ToList(); files.ForEach(f => f.Processed = false); _cabManager.OnProgress += CabManagerOnProgress; try { List <CabFile> parameterFiles; int nbFilesProcessed; switch (action) { case Action.Archive: parameterFiles = files.Select(f => CabFile.NewToPack(f.ArchivePath, f.PathInArchive.ToCleanRelativePathWin(), ((IFileToArchive)f).SourcePath)).ToList(); nbFilesProcessed = _cabManager.PackFileSet(parameterFiles); break; case Action.Extract: parameterFiles = files.Select(f => CabFile.NewToExtract(f.ArchivePath, f.PathInArchive.ToCleanRelativePathWin(), ((IFileInArchiveToExtract)f).ExtractionPath)).ToList(); nbFilesProcessed = _cabManager.ExtractFileSet(parameterFiles); break; case Action.Delete: parameterFiles = files.Select(f => CabFile.NewToDelete(f.ArchivePath, f.PathInArchive.ToCleanRelativePathWin())).ToList(); nbFilesProcessed = _cabManager.DeleteFileSet(parameterFiles); break; case Action.Move: parameterFiles = files.Select(f => CabFile.NewToMove(f.ArchivePath, f.PathInArchive.ToCleanRelativePathWin(), ((IFileInArchiveToMove)f).NewRelativePathInArchive)).ToList(); nbFilesProcessed = _cabManager.MoveFileSet(parameterFiles); break; default: throw new ArgumentOutOfRangeException(nameof(action), action, null); } for (int i = 0; i < parameterFiles.Count; i++) { files[i].Processed = parameterFiles[i].Processed; } return(nbFilesProcessed); } catch (OperationCanceledException) { throw; } catch (Exception e) { throw new ArchiverException(e.Message, e); } finally { _cabManager.OnProgress -= CabManagerOnProgress; } }
public void Main() { Console.WriteLine("Creating dumb file."); File.WriteAllText(@"my_source_file.txt", @"my content"); var cabManager = CabManager.New(); cabManager.SetCompressionLevel(CabCompressionLevel.None); cabManager.SetCancellationToken(null); cabManager.OnProgress += CabManagerOnProgress; // Add files to a new or existing cabinet Console.WriteLine("Adding file to cabinet."); var nbProcessed = cabManager.PackFileSet(new List <IFileToAddInCab> { CabFile.NewToPack(@"archive.cab", @"folder\file.txt", @"my_source_file.txt") }); Console.WriteLine($" -> {nbProcessed} files were added to a cabinet."); // List all the files in a cabinet var filesInCab = cabManager.ListFiles(@"archive.cab").ToList(); Console.WriteLine("Listing files:"); foreach (var fileInCab in filesInCab) { Console.WriteLine($" * {fileInCab.RelativePathInCab}: {fileInCab.LastWriteTime}, {fileInCab.SizeInBytes}, {fileInCab.FileAttributes}"); } // Extract files to external paths Console.WriteLine("Extract file from cabinet."); nbProcessed = cabManager.ExtractFileSet(new List <IFileInCabToExtract> { CabFile.NewToExtract(@"archive.cab", @"folder\file.txt", @"extraction_path.txt") }); Console.WriteLine($" -> {nbProcessed} files were extracted from a cabinet."); // Move files within a cabinet var filesToMove = filesInCab.Select(f => CabFile.NewToMove(f.CabPath, f.RelativePathInCab, $"subfolder/{f.RelativePathInCab}")).ToList(); Console.WriteLine("Moving files within a cabinet."); nbProcessed = cabManager.MoveFileSet(filesToMove); Console.WriteLine($" -> {nbProcessed} files were moved within the cabinet."); Console.WriteLine("Listing files that were processed."); foreach (var file in filesToMove.Where(f => f.Processed)) { Console.WriteLine($" * {file.RelativePathInCab}"); } // Delete files in a cabinet Console.WriteLine("Delete file in cabinet."); nbProcessed = cabManager.DeleteFileSet(filesToMove.Select(f => CabFile.NewToDelete(f.CabPath, f.NewRelativePathInCab))); Console.WriteLine($" -> {nbProcessed} files were deleted from a cabinet."); }
public MSCabCompression(Stream stream) { this.stream = stream; var signature = stream.ReadASCII(4); if (signature != "MSCF") { throw new InvalidDataException("Not a Microsoft CAB package!"); } stream.Position += 12; var filesOffset = stream.ReadUInt32(); stream.Position += 6; var folderCount = stream.ReadUInt16(); var fileCount = stream.ReadUInt16(); if (stream.ReadUInt16() != 0) { throw new InvalidDataException("Only plain packages (without reserved header space or prev/next archives) are supported!"); } stream.Position += 4; folders = new CabFolder[folderCount]; for (var i = 0; i < folderCount; i++) { folders[i] = new CabFolder(stream); if (folders[i].CompressionType != 1) { throw new InvalidDataException("Compression type is not supported"); } } files = new CabFile[fileCount]; stream.Seek(filesOffset, SeekOrigin.Begin); for (var i = 0; i < fileCount; i++) { files[i] = new CabFile(stream); } }
public static CabFile FromContext(string name, IAttributeContext attributeContext) { var result = new CabFile(name); var compressionLevel = attributeContext.GetInheritedAttribute("compressionLevel"); result.CompressionLevel = compressionLevel ?? "none"; var splitStr = attributeContext.GetInheritedAttribute("split") ?? "1"; if (!int.TryParse(splitStr, out var split)) { throw new SwixItemParsingException($"Can't parse split number for cabFile '{name}'"); } if (split <= 0 || split >= 100) { throw new SwixItemParsingException($"Split number must be positive integer less than 100 in the cabFile '{name}'"); } result.Split = split; return(result); }
/// <summary> /// The main execution method for the get-childitem command. /// </summary> protected override void ProcessRecord() { if (_paths == null || _paths.Length == 0) { WriteVerbose("path is null or 0 length."); _paths = new string[] { string.Empty }; } WriteVerbose("Path:" + String.Join(",", Path)); WriteVerbose("LiteralPath:" + String.Join(",", LiteralPath)); WriteVerbose("_paths:" + String.Join(",", _paths)); WriteVerbose("_suppressWildcardExpansion:" + _suppressWildcardExpansion.ToString()); WriteVerbose("Classic:" + Classic.ToString()); WriteVerbose("Next:" + Next.ToString()); WriteVerbose("Wsn:" + Wsn.ToString()); WriteVerbose("Directory:" + Directory.ToString()); WriteVerbose("ZipFile:" + ZipFile.ToString()); WriteVerbose("CabFile:" + CabFile.ToString()); WriteVerbose("WsnFile:" + WsnFile.ToString()); foreach (string path in _paths) { WriteVerbose("path:" + path); // バイナリモジュールから呼べるTest-PathやChildItem的なメソッドでLiteralPathフラグが使えないので、 // あらかじめエスケープしたパスを用意しておき必要な場合はそれを使う var escapedPath = System.Text.RegularExpressions.Regex.Replace(path, "([\\[\\]])", "`$1"); WriteVerbose("escapedPath:" + escapedPath); switch (ParameterSetName) { case childrenSet: case literalChildrenSet: var scenarioFullNames = new List <string>(); // `lscw ゴブリンの洞窟`と指定したとき、ChildItemだけだとゴブリンの洞窟以下のファイルに対して // GetScenarioSummaryをしてしまうため、フォルダ自体にGetScenarioSummaryする処理 // -----------------------👇ここから👇----------------------- if (InvokeProvider.Item.Exists(path, true, _suppressWildcardExpansion)) { WriteVerbose("path is exists."); if (InvokeProvider.Item.IsContainer((_suppressWildcardExpansion ? escapedPath : path))) { WriteVerbose("path is directory."); // 上の条件分岐で存在しているディレクトリに対してしかGet-Itemは動かないのでここで例外は起こらないはず var items = InvokeProvider.Item.Get(new string[] { path }, true, _suppressWildcardExpansion) ?? Enumerable.Empty <PSObject>(); foreach (var item in items) { if (item.BaseObject is System.IO.FileSystemInfo info) { try { // フルパスからシナリオ情報を取得する WriteVerbose("fullName:" + info.FullName); var scenarioSummary = CardWirthScenario.GetScenarioSummary(info.FullName); // 次のChildItemで同じフォルダを見る可能性があるので // 処理対象外にするためにシナリオのパスを覚えておく scenarioFullNames.Add(scenarioSummary.FullName); // シナリオ形式のフィルタリング if (Classic && scenarioSummary.ScenarioType != ScenarioType.Classic) { continue; } else if (Next && scenarioSummary.ScenarioType != ScenarioType.Next) { continue; } else if (Wsn && scenarioSummary.ScenarioType != ScenarioType.Wsn) { continue; } // 格納形式のフィルタリング if (Directory && scenarioSummary.ContainerType != ContainerType.Directory) { continue; } else if (ZipFile && scenarioSummary.ContainerType != ContainerType.ZipFile) { continue; } else if (CabFile && scenarioSummary.ContainerType != ContainerType.CabFile) { continue; } else if (WsnFile && scenarioSummary.ContainerType != ContainerType.WsnFile) { continue; } WriteObject(scenarioSummary); } catch (Exception ex) { WriteVerbose("error:" + ex.Message); continue; } } } } } // -----------------------👆ここまで👆----------------------- // ここから指定したパス以下のファイル・フォルダを調査する var childItems = Enumerable.Empty <PSObject>(); try { childItems = InvokeProvider.ChildItem.Get((_suppressWildcardExpansion ? escapedPath : path), _recurse) ?? Enumerable.Empty <PSObject>(); } catch (PSNotSupportedException notSupported) { WriteError(new ErrorRecord(notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError(new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError(new ErrorRecord(providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError(new ErrorRecord(pathNotFound.ErrorRecord, pathNotFound)); continue; } foreach (var childItem in childItems) { WriteVerbose("childItem:" + childItem); if (childItem.BaseObject is System.IO.FileSystemInfo info) { // Get-ChildItemでとってきた要素すべてを調査していてはきりがないのである程度選別する; if (info is System.IO.FileInfo file) { // 拡張子がサポート対象外のファイルの場合、シナリオ情報取得をスキップする var extension = System.IO.Path.GetExtension(file.FullName).ToLower(); if (extension != ".zip" && extension != ".cab" && extension != ".wsn") { WriteVerbose("path is not supported archive file. skipped acquisition of scenario information."); continue; } } // 調査済みパスの場合、シナリオ情報取得をスキップする if (scenarioFullNames.Contains(info.FullName)) { WriteVerbose("path has been investigated. skipped acquisition of scenario information."); continue; } try { // フルパスからシナリオ情報を取得する // TODO:ディレクトリの場合、シナリオではないのならエラー表示を無視したい // 再帰のとき、エラー処理をどうするか考え中 var scenarioSummary = CardWirthScenario.GetScenarioSummary(info.FullName); // シナリオ形式のフィルタリング if (Classic && scenarioSummary.ScenarioType != ScenarioType.Classic) { continue; } else if (Next && scenarioSummary.ScenarioType != ScenarioType.Next) { continue; } else if (Wsn && scenarioSummary.ScenarioType != ScenarioType.Wsn) { continue; } // 格納形式のフィルタリング if (Directory && scenarioSummary.ContainerType != ContainerType.Directory) { continue; } else if (ZipFile && scenarioSummary.ContainerType != ContainerType.ZipFile) { continue; } else if (CabFile && scenarioSummary.ContainerType != ContainerType.CabFile) { continue; } else if (WsnFile && scenarioSummary.ContainerType != ContainerType.WsnFile) { continue; } WriteObject(scenarioSummary); } catch (Exception ex) { WriteVerbose("error:" + ex.Message); continue; } } } break; default: break; } } }