public virtual void Init() { _baseDirectory = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..")); _paths = new PathUtility(); _win32 = new Win32IO(); _scanner = new FileSystemScanner(_paths, _win32); }
/// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> /// <remarks>The <paramref name="outputStream"/> is closed after creation.</remarks> public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; using (outputStream_ = new ZipOutputStream(outputStream)) { outputStream_.SetLevel((int)CompressionLevel); outputStream_.UseZip64 = UseZip64; var scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += ProcessFile; if (this.CreateEmptyDirectories) { scanner.ProcessDirectory += ProcessDirectory; } if (events_ != null) { if (events_.FileFailure != null) { scanner.FileFailure += events_.FileFailure; } if (events_.DirectoryFailure != null) { scanner.DirectoryFailure += events_.DirectoryFailure; } } scanner.Scan(sourceDirectory, recurse); } }
public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { this.NameTransform = new ZipNameTransform(sourceDirectory); this.sourceDirectory_ = sourceDirectory; using (this.outputStream_ = new ZipOutputStream(outputStream)) { if (this.password_ != null) { this.outputStream_.Password = this.password_; } this.outputStream_.UseZip64 = this.UseZip64; FileSystemScanner fileSystemScanner = new FileSystemScanner(fileFilter, directoryFilter); FileSystemScanner fileSystemScanner2 = fileSystemScanner; fileSystemScanner2.ProcessFile = (ProcessFileHandler)Delegate.Combine(fileSystemScanner2.ProcessFile, new ProcessFileHandler(this.ProcessFile)); if (this.CreateEmptyDirectories) { FileSystemScanner fileSystemScanner3 = fileSystemScanner; fileSystemScanner3.ProcessDirectory = (ProcessDirectoryHandler)Delegate.Combine(fileSystemScanner3.ProcessDirectory, new ProcessDirectoryHandler(this.ProcessDirectory)); } if (this.events_ != null) { if (this.events_.FileFailure != null) { FileSystemScanner fileSystemScanner4 = fileSystemScanner; fileSystemScanner4.FileFailure = (FileFailureHandler)Delegate.Combine(fileSystemScanner4.FileFailure, this.events_.FileFailure); } if (this.events_.DirectoryFailure != null) { FileSystemScanner fileSystemScanner5 = fileSystemScanner; fileSystemScanner5.DirectoryFailure = (DirectoryFailureHandler)Delegate.Combine(fileSystemScanner5.DirectoryFailure, this.events_.DirectoryFailure); } } fileSystemScanner.Scan(sourceDirectory, recurse); } }
/// <summary> /// Performs a directory deletion. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="directory">The directory to delete.</param> /// <param name="execute">if set to true, the operation gets executed.</param> private void PerformDirectoryDeletionOperation(IFileSystem fileSystem, IDirectoryInfo directory, bool execute) { var eventArgs = new DirectoryDeletionEventArgs(directory.FullName); this.OnDeletingDirectory(eventArgs); var directoryScanner = new FileSystemScanner(directory); directoryScanner.FileFound += (sender, e) => this.OnProceededFile(new FileProceededEventArgs(e.File.FullName, e.File.Length)); directoryScanner.Start(); if (execute) { try { fileSystem.DeleteDirectory(directory); this.OnDeletedDirectory(eventArgs); } catch (AccessException) { this.OnDirectoryDeletionError(new DirectoryDeletionEventArgs(directory.FullName)); } } }
/// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; using (outputStream_ = new ZipOutputStream(outputStream)) { FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += new ProcessFileDelegate(ProcessFile); if (this.CreateEmptyDirectories) { scanner.ProcessDirectory += new ProcessDirectoryDelegate(ProcessDirectory); } if (events_ != null) { if (events_.FileFailure != null) { scanner.FileFailure += events_.FileFailure; } if (events_.DirectoryFailure != null) { scanner.DirectoryFailure += events_.DirectoryFailure; } } scanner.Scan(sourceDirectory, recurse); } }
public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); _sourceDirectory = sourceDirectory; using (_outputStream = new ZipOutputStream(outputStream)) { if (_password != null) { _outputStream.Password = _password; } _outputStream.UseZip64 = UseZip64; FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile = (ProcessFileHandler)Delegate.Combine(scanner.ProcessFile, new ProcessFileHandler(ProcessFile)); if (CreateEmptyDirectories) { scanner.ProcessDirectory = (ProcessDirectoryHandler)Delegate.Combine(scanner.ProcessDirectory, new ProcessDirectoryHandler(ProcessDirectory)); } if (_events != null) { if (_events.FileFailure != null) { scanner.FileFailure = (FileFailureHandler)Delegate.Combine(scanner.FileFailure, _events.FileFailure); } if (_events.DirectoryFailure != null) { scanner.DirectoryFailure = (DirectoryFailureHandler)Delegate.Combine(scanner.DirectoryFailure, _events.DirectoryFailure); } } scanner.Scan(sourceDirectory, recurse); } }
public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; using (outputStream_ = new ZipOutputStream(outputStream)) { if (password_ != null) { outputStream_.Password = password_; } outputStream_.UseZip64 = UseZip64; FileSystemScanner fileSystemScanner = new FileSystemScanner(fileFilter, directoryFilter); fileSystemScanner.ProcessFile = (ProcessFileHandler)Delegate.Combine(fileSystemScanner.ProcessFile, new ProcessFileHandler(ProcessFile)); if (CreateEmptyDirectories) { fileSystemScanner.ProcessDirectory = (ProcessDirectoryHandler)Delegate.Combine(fileSystemScanner.ProcessDirectory, new ProcessDirectoryHandler(ProcessDirectory)); } if (events_ != null) { if (events_.FileFailure != null) { fileSystemScanner.FileFailure = (FileFailureHandler)Delegate.Combine(fileSystemScanner.FileFailure, events_.FileFailure); } if (events_.DirectoryFailure != null) { fileSystemScanner.DirectoryFailure = (DirectoryFailureHandler)Delegate.Combine(fileSystemScanner.DirectoryFailure, events_.DirectoryFailure); } } fileSystemScanner.Scan(sourceDirectory, recurse); } }
void ListFileSystem(string directory, bool recurse, string fileFilter, string directoryFilter) { var scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessDirectory += ListDir; scanner.ProcessFile += ListFile; scanner.Scan(directory, recurse); }
void ListFileSystem(string directory, bool recurse, string fileFilter, string directoryFilter) { FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessDirectory += new ProcessDirectoryHandler(ListDir); scanner.ProcessFile += new ProcessFileHandler(ListFile); scanner.Scan(directory, recurse); }
/// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { entryFactory_.NameTransform = new ZipNameTransform(sourceDirectory); using (outputStream_ = new ZipOutputStream(outputStream)) { FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += new ProcessFileHandler(ProcessFile); scanner.Scan(sourceDirectory, recurse); } }
private List <LogEjecucion> VisitarRuta(string RutaLog, int EjecucionConfiguracionId, out List <string> filenames, out bool existenLeidos) { List <LogEjecucion> logErrors = new List <LogEjecucion>(); filenames = new List <string>(); existenLeidos = false; _eventLog.CrearLog("Buscando archivos de log en la ruta: " + RutaLog); try { List <string> files = FileSystemScanner.UrlDirectoryDownload(RutaLog, out string mensaje); foreach (string filename in files.Where(x => x.Contains(".txt"))) { _eventLog.CrearLog("Leyendo el archivo: " + filename); string[] filenameArray = filename.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); string filenameI = filenameArray[filenameArray.Length - 1]; if (filenameI != "LogEjec.txt" && ValidarFechaArchivo(filenameI)) { _eventLog.CrearLog("Obteniendo la bitacora de logs leidos de: " + filename); Dictionary <string, dynamic> P = new Dictionary <string, dynamic> { { "Opcion", 2 }, { "EjecucionConfiguracionId", EjecucionConfiguracionId }, { "EjecucionConfiguracionLecturaDescripcion", filenameI }, { "Baja", false } }; List <EjecucionConfiguracionLectura> lectura = _daoLectura.Consultar <EjecucionConfiguracionLectura>(P).ToList(); string urlFile = Path.Combine(RutaLog, filenameI); string fileText = FileSystemScanner.GetLogFile(urlFile, out string mensajeArchivo); logErrors.AddRange(FileSystemScanner.MapLogText <LogEjecucion>(fileText)); if (lectura.Any()) { existenLeidos = true; logErrors = logErrors.OrderBy(x => x.Fecha).Skip(lectura[0].NumeroRegistros).ToList(); } filenames.Add(filenameI); } } } catch (Exception ex) { string InnerExcepcionResult = (ex.InnerException != null ? ex.InnerException?.ToString() : "").Trim(); string ErrorResult = ("Error en el proceso: " + ex.Message + ". " + InnerExcepcionResult).Trim(); LogExcepcion logEx = GenerarLogExcepcion("Proceso de Ejecuciones", ErrorResult, ErrorResult, "750", InnerExcepcionResult, "Proceso de Ejecuciones"); m = RegistrarExcepcion(logEx, null); logErrors = new List <LogEjecucion>(); string error = string.Format("Hubo un problema con el proceso. {0}. {1}.", ex.Message, ex.InnerException?.ToString()); _eventLog.CrearLog(error); } return(logErrors); }
/// <summary> /// Add files to an archive /// </summary> /// <param name="fileSpecs">The specification for files to add.</param> void Add(ArrayList fileSpecs) { string zipFileName = fileSpecs[0] as string; if (Path.GetExtension(zipFileName).Length == 0) { zipFileName = Path.ChangeExtension(zipFileName, ".zip"); } fileSpecs.RemoveAt(0); ZipFile zipFile; try { if (File.Exists(zipFileName)) { zipFile = new ZipFile(zipFileName); } else { zipFile = ZipFile.Create(zipFileName); } using (zipFile) { zipFile.Password = password_; zipFile.UseZip64 = useZip64_; zipFile.BeginUpdate(); activeZipFile_ = zipFile; foreach (string spec in fileSpecs) { string path = Path.GetDirectoryName(Path.GetFullPath(spec)); string fileSpec = Path.GetFileName(spec); zipFile.NameTransform = new ZipNameTransform(path); FileSystemScanner scanner = new FileSystemScanner(WildcardToRegex(fileSpec)); scanner.ProcessFile = new ProcessFileHandler(ProcessFile); scanner.ProcessDirectory = new ProcessDirectoryHandler(ProcessDirectory); scanner.Scan(path, recursive_); } zipFile.CommitUpdate(); } } catch (Exception ex) { Console.WriteLine("Problem adding to archive - '{0}'", ex.Message); } }
/// <summary> /// Create archives based on specifications passed and internal state /// </summary> void Create(ArrayList fileSpecs) { string zipFileName = fileSpecs[0] as string; if (Path.GetExtension(zipFileName).Length == 0) { zipFileName = Path.ChangeExtension(zipFileName, ".zip"); } fileSpecs.RemoveAt(0); if ((overwriteFiles == Overwrite.Never) && File.Exists(zipFileName)) { Console.Error.WriteLine("File {0} already exists", zipFileName); return; } try { using (ZipFile zf = ZipFile.Create(zipFileName)) { zf.Password = password_; zf.UseZip64 = useZip64_; zf.BeginUpdate(); activeZipFile_ = zf; foreach (string spec in fileSpecs) { // This can fail with wildcards in spec... string path = Path.GetDirectoryName(Path.GetFullPath(spec)); string fileSpec = Path.GetFileName(spec); zf.NameTransform = new ZipNameTransform(path); FileSystemScanner scanner = new FileSystemScanner(WildcardToRegex(fileSpec)); scanner.ProcessFile = new ProcessFileHandler(ProcessFile); scanner.ProcessDirectory = new ProcessDirectoryHandler(ProcessDirectory); scanner.Scan(path, recursive_); } zf.CommitUpdate(); } } catch (Exception ex) { Console.WriteLine("Problem creating archive - '{0}'", ex.Message); } }
static void ExtractFirmware(string filePath) { var targetDir = Path.Combine(Environment.CurrentDirectory, $"{filePath}.extracted"); var targetFsDir = Path.Combine(targetDir, "file_system"); if (!Directory.Exists(targetFsDir)) { Directory.CreateDirectory(targetFsDir); } var firmwareFile = new FirmwareFile(filePath); var fileSystemScanner = new FileSystemScanner(firmwareFile.ContiguousRomData); fileSystemScanner.ExtractFileSystem(targetFsDir); }
public void Run() { var path = @"D:\tmp\xup"; var scanner = new FileSystemScanner(); var versioned = scanner.ScanForResources(path, "V", ".sql"); var repeatable = scanner.ScanForResources(path, "R", ".sql"); var resources = versioned.Concat(repeatable); foreach (var r in resources) { var fileName = Path.GetFileName(r.Path); var m = fileName.ParseMigration(); Console.WriteLine(m); } }
/// <summary> /// Create a zip file. /// </summary> /// <param name="zipFileName">The name of the zip file to create.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The file filter to apply.</param> /// <param name="directoryFilter">The directory filter to apply.</param> public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(true, sourceDirectory); this.sourceDirectory = sourceDirectory; outputStream = new ZipOutputStream(File.Create(zipFileName)); try { FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += new ProcessFileDelegate(ProcessFile); if (this.CreateEmptyDirectories) { scanner.ProcessDirectory += new ProcessDirectoryDelegate(ProcessDirectory); } scanner.Scan(sourceDirectory, recurse); } finally { outputStream.Close(); } }
override protected bool Prebuild() { string directory = MainForm.Settings.findInFilesDir.Value; if (string.IsNullOrEmpty(directory)) { directory = Directory.GetCurrentDirectory(); } FileSystemScanner scanner = new FileSystemScanner( directory, GetFilterText(), MainForm.Settings.findInFilesIgnoreDir.Value); thread = new Thread(new ThreadStart(scanner.Scan)); thread.Start(); thread.Join(new TimeSpan(0, 0, MainForm.Settings.fileIncrementalSearchTimeout.Value)); if (scanner.done) { if (scanner.error != null) { MainForm.Dialogs.ShowInfo("Error", scanner.error); } } else { MainForm.Dialogs.ShowInfo( "Error", "File system scanning timeout (" + MainForm.Settings.fileIncrementalSearchTimeout.name + "=" + MainForm.Settings.fileIncrementalSearchTimeout.Value + ")" ); return(false); } filesList.Clear(); string currentDirectory = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar; foreach (string file in scanner.files) { filesList.Add(file.StartsWith(currentDirectory) ? file.Substring(currentDirectory.Length) : file); } return(true); }
/// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> /// <remarks>The <paramref name="outputStream"/> is closed after creation.</remarks> public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; using (outputStream_ = new ZipOutputStream(outputStream)) { #if !NETCF_1_0 if (password_ != null) { outputStream_.Password = password_; } #endif outputStream_.UseZip64 = UseZip64; var scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += ProcessFile; if (CreateEmptyDirectories) { scanner.ProcessDirectory += ProcessDirectory; } if (events_ != null) { if (events_.FileFailure != null) { scanner.FileFailure += events_.FileFailure; } if (events_.DirectoryFailure != null) { scanner.DirectoryFailure += events_.DirectoryFailure; } } scanner.Scan(sourceDirectory, recurse); } }
/// <summary> /// Create archives based on specifications passed and internal state /// </summary> void Create(string zipFileName, ArrayList fileSpecs, ref ToolStripProgressBar ProgressBar) { if (Path.GetExtension(zipFileName).Length == 0) { zipFileName = Path.ChangeExtension(zipFileName, ".zip"); } try { using (ZipFile zf = ZipFile.Create(zipFileName)) { zf.BeginUpdate(); activeZipFile_ = zf; foreach (string spec in fileSpecs) { // This can fail with wildcards in spec... string path = Path.GetDirectoryName(Path.GetFullPath(spec)); string fileSpec = Path.GetFileName(spec); zf.NameTransform = new ZipNameTransform(Settings.Global.Properties["POLPath"]); FileSystemScanner scanner = new FileSystemScanner(fileSpec); scanner.ProcessFile = new ProcessFileHandler(ProcessFile); scanner.Scan(path, false); ProgressBar.PerformStep(); } zf.CommitUpdate(); ProgressBar.PerformStep(); } } catch (Exception ex) { ExceptionBox.ExceptionForm tmp = new ExceptionBox.ExceptionForm(ref ex); tmp.ShowDialog(); } }
public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; ZipOutputStream zipOutputStream = (outputStream_ = new ZipOutputStream(outputStream)); try { if (password_ != null) { outputStream_.Password = password_; } outputStream_.UseZip64 = UseZip64; FileSystemScanner fileSystemScanner = new FileSystemScanner(fileFilter, directoryFilter); fileSystemScanner.ProcessFile = (ProcessFileHandler)global::System.Delegate.Combine((global::System.Delegate)fileSystemScanner.ProcessFile, (global::System.Delegate) new ProcessFileHandler(ProcessFile)); if (CreateEmptyDirectories) { fileSystemScanner.ProcessDirectory = (ProcessDirectoryHandler)global::System.Delegate.Combine((global::System.Delegate)fileSystemScanner.ProcessDirectory, (global::System.Delegate) new ProcessDirectoryHandler(ProcessDirectory)); } if (events_ != null) { if (events_.FileFailure != null) { fileSystemScanner.FileFailure = (FileFailureHandler)global::System.Delegate.Combine((global::System.Delegate)fileSystemScanner.FileFailure, (global::System.Delegate)events_.FileFailure); } if (events_.DirectoryFailure != null) { fileSystemScanner.DirectoryFailure = (DirectoryFailureHandler)global::System.Delegate.Combine((global::System.Delegate)fileSystemScanner.DirectoryFailure, (global::System.Delegate)events_.DirectoryFailure); } } fileSystemScanner.Scan(sourceDirectory, recurse); } finally { ((global::System.IDisposable)zipOutputStream)?.Dispose(); } }
public static void EachAllFile(System.Action <string> fun) { #if UNITY_EDITOR || UNITY_IPHONE || UNITY_STANDALONE string fullfile = ResourcesPath.streamingAssetsPath; FileSystemScanner scanner = new FileSystemScanner("", ""); scanner.ProcessFile = (object sender, ScanEventArgs e) => { fun(e.Name.Substring(fullfile.Length).Replace('\\', '/')); }; scanner.Scan(fullfile, true); #elif UNITY_ANDROID // 安卓平台的,数据存储在apk包当中 Init(); ApkFile.EachAllFile( (string file) => { if (file.StartsWith("assets/")) { fun(file.Substring(7)); } }); #endif }
/// <summary> /// Backups a directory recursively to another directory (without deletions). /// </summary> /// <param name="sourceDirectory">The source directory.</param> /// <param name="targetDirectory">The target directory.</param> /// <param name="execute">if set to true, the modifications, creations and deletions will be executed executed.</param> protected void BackupDirectoryRecursively(IDirectoryInfo sourceDirectory, IDirectoryInfo targetDirectory, bool execute) { if (!sourceDirectory.Exists) { throw new ArgumentException("The source directory doesn't exist.", Reflector.GetMemberName(() => sourceDirectory)); } if (!targetDirectory.Exists) { throw new ArgumentException("The target directory doesn't exist.", Reflector.GetMemberName(() => targetDirectory)); } var rootScanner = new FileSystemScanner(sourceDirectory); IDirectoryInfo currentTargetDirectory = targetDirectory; rootScanner.DirectoryFound += (sender, e) => { this.CheckPause(); if (this.IsStopped) { rootScanner.Stop(); return; } //Assemble the path of the new target directory string newTargetDirectoryPath = this.TargetFileSystem.CombinePath(currentTargetDirectory.FullName, e.Directory.Name); bool newTargetDirectoryExists = this.TargetFileSystem.DirectoryExists(newTargetDirectoryPath); bool newTargetDirectoryIsExcluded = this.excludedPaths.Any(path => NormalizePath(newTargetDirectoryPath).StartsWith(path)); //Check if the new target directory exists and if not, create it if (!newTargetDirectoryExists && !newTargetDirectoryIsExcluded) { this.PerformDirectoryCreationOperation(this.TargetFileSystem, e.Directory, currentTargetDirectory, execute); } currentTargetDirectory = this.TargetFileSystem.GetDirectoryInfo(newTargetDirectoryPath); }; rootScanner.DirectoryProceeded += (sender, e) => { this.CheckPause(); if (this.IsStopped) { rootScanner.Stop(); return; } //When a directory has been completely proceeded, jump to the parent directory of the target directory if (currentTargetDirectory.Parent != null) { currentTargetDirectory = currentTargetDirectory.Parent; } }; rootScanner.FileFound += (sender, e) => { this.CheckPause(); if (this.IsStopped) { rootScanner.Stop(); return; } //Assemble the path of the target file string targetFilePath = this.TargetFileSystem.CombinePath(currentTargetDirectory.FullName, e.File.Name); //The file must not be a contained in any subfolder of the excluded folders if (!this.excludedPaths.Any(path => NormalizePath(targetFilePath).StartsWith(path))) { //Check if the target file exists in the target directory and if not, create it if (!this.TargetFileSystem.FileExists(targetFilePath)) { this.PerformFileCreationOperation(this.SourceFileSystem, this.TargetFileSystem, e.File, currentTargetDirectory, execute); //Add the created file to the proceeded files, to avoid a double-counting this.proceededFilePaths.Add(this.TargetFileSystem.CombinePath(currentTargetDirectory.FullName, e.File.Name)); } //Check if the source file is newer than the target file else if (IsFileModified(e.File, this.TargetFileSystem.GetFileInfo(targetFilePath))) { this.PerformFileModificationOperation(this.SourceFileSystem, this.TargetFileSystem, e.File, currentTargetDirectory, execute); //Add the created file to the proceeded files, to avoid a double-counting this.proceededFilePaths.Add(this.TargetFileSystem.CombinePath(currentTargetDirectory.FullName, e.File.Name)); } this.OnProceededFile(new FileProceededEventArgs(e.File.FullName, e.File.Length)); } }; rootScanner.Start(); }
/// <summary> /// Checks the source directory recursively for directories and files that are not in the target directory and deletes them. /// </summary> /// <param name="sourceDirectory">The source directory.</param> /// <param name="targetDirectory">The target directory.</param> /// <param name="execute">if set to true, the modifications, creations and deletions will be executed executed.</param> protected void CheckDeletionsRecursively(IDirectoryInfo sourceDirectory, IDirectoryInfo targetDirectory, bool execute) { if (!sourceDirectory.Exists) { throw new ArgumentException("The source directory doesn't exist.", Reflector.GetMemberName(() => sourceDirectory)); } if (!targetDirectory.Exists) { throw new ArgumentException("The target directory doesn't exist.", Reflector.GetMemberName(() => targetDirectory)); } var rootScanner = new FileSystemScanner(sourceDirectory); IDirectoryInfo currentTargetDirectory = targetDirectory; rootScanner.DirectoryFound += (sender, e) => { this.CheckPause(); if (this.IsStopped) { rootScanner.Stop(); return; } string newTargetDirectoryPath = this.TargetFileSystem.CombinePath(currentTargetDirectory.FullName, e.Directory.Name); bool newTargetDirectoryExists = this.SourceFileSystem.DirectoryExists(newTargetDirectoryPath); bool newTargetDirectoryIsExcluded = this.deletedDirectoryPaths.Any(path => NormalizePath(newTargetDirectoryPath).StartsWith(path)); // Delete the directory if it doesn't exist in the source directory if (!newTargetDirectoryExists && !newTargetDirectoryIsExcluded) { // If we perform a preview, add the directory that gets deleted to the deleted paths, // so that the subdirectories don't get included. if (!execute) { this.deletedDirectoryPaths.Add(NormalizePath(newTargetDirectoryPath)); } this.PerformDirectoryDeletionOperation(this.TargetFileSystem, e.Directory, execute); } currentTargetDirectory = this.SourceFileSystem.GetDirectoryInfo(newTargetDirectoryPath); }; rootScanner.DirectoryProceeded += (sender, e) => { this.CheckPause(); if (this.IsStopped) { rootScanner.Stop(); return; } //When a directory has been completely proceeded, jump to the parent directory of the target directory currentTargetDirectory = currentTargetDirectory.Parent; }; rootScanner.FileFound += (sender, e) => { this.CheckPause(); if (this.IsStopped) { rootScanner.Stop(); return; } string targetFilePath = this.TargetFileSystem.CombinePath(currentTargetDirectory.FullName, e.File.Name); //Save the file path and length for the case that the file gets deleted, //so that the FileProceeded event can be raises properly string sourceFilePath = e.File.FullName; long sourceFileLength = e.File.Length; bool targetFileExists = this.SourceFileSystem.FileExists(targetFilePath); bool targetFileIsExcluded = this.deletedDirectoryPaths.Any(path => NormalizePath(targetFilePath).StartsWith(path)); //Check if the file doesn't exist in the target directory if (!targetFileExists && !targetFileIsExcluded) { this.PerformFileDeletionOperation(this.TargetFileSystem, e.File, execute); //Add the deleted file to the proceeded files, to avoid a double-counting //(this can happen when the deletion of the file fails) this.proceededFilePaths.Add(e.File.Name); } this.OnProceededFile(new FileProceededEventArgs(sourceFilePath, sourceFileLength)); }; rootScanner.Start(); }
private void Search(string directory, Regex regex, string pattern, bool ignoreCase, string filter, string ignoreDirs) { positions = new List <Position>(); buffer = new Buffer(null, "Find in files results", SettingsMode.Normal); buffer.showEncoding = false; buffer.Controller.isReadonly = true; lines = buffer.Controller.Lines; lines.ClearAllUnsafely(); bool needCutCurrent = false; if (string.IsNullOrEmpty(directory)) { directory = Directory.GetCurrentDirectory(); needCutCurrent = true; } FileSystemScanner scanner = new FileSystemScanner(directory, filter, ignoreDirs); scanner.Scan(); if (scanner.error != null) { AddLine("Error: File list reading error: " + scanner.error, Ds.Error); } fsScanComplete = true; string currentDirectory = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar; List <IndexAndLength> indices = new List <IndexAndLength>(); CompareInfo ci = ignoreCase ? CultureInfo.InvariantCulture.CompareInfo : null; int remainsMatchesCount = 2000000; string stopReason = null; foreach (string file in scanner.files) { if (isStopped) { if (stopReason == null) { stopReason = "STOPPED"; } break; } string text = null; try { text = File.ReadAllText(file); } catch (IOException e) { --remainsMatchesCount; if (remainsMatchesCount < 0) { isStopped = true; stopReason = "TOO MANY LINES"; break; } AddLine(file + ": " + e.Message, Ds.Error); continue; } indices.Clear(); if (regex != null) { MatchCollection matches = regex.Matches(text); if (matches.Count == 0) { continue; } foreach (Match match in matches) { indices.Add(new IndexAndLength(match.Index, match.Length)); } } else { int index = ci != null?ci.IndexOf(text, pattern, CompareOptions.IgnoreCase) : text.IndexOf(pattern); if (index == -1) { continue; } while (true) { indices.Add(new IndexAndLength(index, pattern.Length)); index = ci != null?ci.IndexOf(text, pattern, index + 1, CompareOptions.IgnoreCase) : text.IndexOf(pattern, index + 1); if (index == -1) { break; } } } string path = file; if (needCutCurrent && path.StartsWith(currentDirectory)) { path = file.Substring(currentDirectory.Length); } int offset = 0; int currentLineIndex = 0; foreach (IndexAndLength indexAndLength in indices) { int index = indexAndLength.index; int length = indexAndLength.length; int lineEnd = -1; while (true) { int nIndex = text.IndexOf('\n', offset); int rIndex = text.IndexOf('\r', offset); if (nIndex == -1 && rIndex == -1) { lineEnd = text.Length; break; } int nrIndex = System.Math.Min(nIndex, rIndex); if (nrIndex == -1) { nrIndex = nIndex != -1 ? nIndex : rIndex; } if (nrIndex > index) { lineEnd = nrIndex; break; } currentLineIndex++; if (nrIndex == nIndex) { offset = nIndex + 1; } else { if (rIndex + 1 < text.Length || text[rIndex + 1] == '\n') { offset = rIndex + 2; } else { offset = rIndex + 1; } } } --remainsMatchesCount; if (remainsMatchesCount < 0) { isStopped = true; stopReason = "TOO MANY MATCHES"; break; } int trimOffset = 0; int rightTrimOffset = 0; int lineLength = lineEnd - offset; if (index - offset - MaxPartChars > 0) { trimOffset = index - offset - MaxPartChars; } if (lineLength - index + offset - length - MaxPartChars > 0) { rightTrimOffset = lineLength - index + offset - length - MaxPartChars; } if (trimOffset == 0) { int whitespaceLength = CommonHelper.GetFirstSpaces(text, offset, lineLength - rightTrimOffset); if (whitespaceLength > 0 && whitespaceLength <= index - offset) { trimOffset = whitespaceLength; } } positions.Add(new Position(file, new Place(index - offset, currentLineIndex), length)); int index0 = offset + trimOffset; int length0 = lineLength - trimOffset - rightTrimOffset; AddLine(path, (currentLineIndex + 1) + " " + (index - offset + 1), text, index0, length0, index - offset - trimOffset, length); } } if (isStopped) { AddLine("…", Ds.Normal); AddLine(stopReason, Ds.Error); } if (lines.LinesCount == 0) { lines.AddLineUnsafely(new Line(32)); } else { lines.CutLastLineBreakUnsafely(); } buffer.additionKeyMap = new KeyMap(); { KeyAction action = new KeyAction("F&ind\\Navigate to found", ExecuteEnter, null, false); buffer.additionKeyMap.AddItem(new KeyItem(Keys.Enter, null, action)); buffer.additionKeyMap.AddItem(new KeyItem(Keys.None, null, action).SetDoubleClick(true)); } finishBuffer = buffer; mainForm.Invoke(new Setter(CloseAlert)); }
/// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="scanner">For performing the actual file system scan</param> /// <param name="leaveOpen">true to leave <paramref name="outputStream"/> open after the zip has been created, false to dispose it.</param> /// <remarks>The <paramref name="outputStream"/> is closed after creation.</remarks> private void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, FileSystemScanner scanner, bool leaveOpen) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; using (outputStream_ = new ZipOutputStream(outputStream)) { outputStream_.SetLevel((int)CompressionLevel); outputStream_.IsStreamOwner = !leaveOpen; outputStream_.NameTransform = null; // all required transforms handled by us if (false == string.IsNullOrEmpty(password_) && EntryEncryptionMethod != ZipEncryptionMethod.None) { outputStream_.Password = password_; } outputStream_.UseZip64 = UseZip64; scanner.ProcessFile += ProcessFile; if (this.CreateEmptyDirectories) { scanner.ProcessDirectory += ProcessDirectory; } if (events_ != null) { if (events_.FileFailure != null) { scanner.FileFailure += events_.FileFailure; } if (events_.DirectoryFailure != null) { scanner.DirectoryFailure += events_.DirectoryFailure; } } scanner.Scan(sourceDirectory, recurse); } }
/// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="IScanFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="IScanFilter">directory filter</see> to apply.</param> /// <param name="leaveOpen">true to leave <paramref name="outputStream"/> open after the zip has been created, false to dispose it.</param> public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, IScanFilter fileFilter, IScanFilter directoryFilter, bool leaveOpen = false) { var scanner = new FileSystemScanner(fileFilter, directoryFilter); CreateZip(outputStream, sourceDirectory, recurse, scanner, leaveOpen); }