public CustomAssemblyResolver( IDirectoryInfo assemblyDirectory, ILogger logger, DepsJsonUtils depsJsonUtils) { _logger = logger; foreach (var searchDirectory in GetSearchDirectories()) { RemoveSearchDirectory(searchDirectory); } AddSearchDirectory(assemblyDirectory.FullName); _dependencyContext = depsJsonUtils.LoadDependencyContext(assemblyDirectory); var runtimeConfigPath = assemblyDirectory.GetFiles("*.runtimeconfig.dev.json", SearchOption.TopDirectoryOnly) .Concat(assemblyDirectory.GetFiles("*.runtimeconfig.json", SearchOption.TopDirectoryOnly)) .FirstOrDefault(); if (runtimeConfigPath != null) { var runtimeConfigContent = File.ReadAllText(runtimeConfigPath.FullName); foreach (var path in depsJsonUtils.GetAdditionalPaths(runtimeConfigContent)) { AddSearchDirectory(path); } } }
public static bool IsEmpty(this IDirectoryInfo directoryInfo) { const SearchOption AllDirectories = SearchOption.AllDirectories; var anyFile = directoryInfo.GetFiles(Storage.AllPattern, AllDirectories).Any(); var anyDirectory = directoryInfo.GetFiles(Storage.AllPattern, AllDirectories).Any(); return(!anyDirectory && !anyFile); }
private void CopyFilesFromDirectory(IDirectoryInfo sourceDirectory, IDirectoryInfo destinationDirectory) { IFileInfo[] sourceFiles = FilePattern != null?sourceDirectory.GetFiles(FilePattern) : sourceDirectory.GetFiles(); foreach (IFileInfo sourceFile in sourceFiles) { string destFileName = _fileSystem.Path.Combine(destinationDirectory.FullName, sourceFile.Name); CopySingleFile(sourceFile, destFileName); } }
static bool ListDirectory(string[] args) { IFileInfo[] files = currentDirectory.GetFiles(); for (int i = 0; i < files.Length; i++) { Console.Write(files[i].Name); Console.Write("\t\t\t"); Console.Write(files[i].Size); Console.WriteLine(); } return(true); }
private async Task AddDirectoryFilesToTar(TarOutputStream tarArchive, IDirectoryInfo directory) { if (!string.IsNullOrWhiteSpace(GetRelativePath(directory))) { var tarEntry = TarEntry.CreateEntryFromFile(directory.FullName); tarEntry.Name = GetRelativePath(directory); tarArchive.PutNextEntry(tarEntry); } // Write each file to the tar. foreach (var file in directory.GetFiles()) { var tarEntry = TarEntry.CreateEntryFromFile(file.FullName); tarEntry.Name = GetRelativePath(file); tarEntry.Size = file.Length; tarArchive.PutNextEntry(tarEntry); using var fileStream = file.OpenRead(); await fileStream.CopyToAsync(tarArchive); tarArchive.CloseEntry(); } foreach (var childDirectory in directory.GetDirectories()) { await AddDirectoryFilesToTar(tarArchive, childDirectory); } }
private static IDirectoryInfo CopyDirectory(IDirectoryInfo source, IDirectoryInfo destination) { var targetDir = destination.GetDirectories().FirstOrDefault(dir => string.Equals(dir.Name, source.Name, StringComparison.OrdinalIgnoreCase)) ?? destination.CreateSubdirectory(source.Name); foreach (var sourceFile in source.GetFiles()) { var name = sourceFile.Name; var targetFile = targetDir.GetFiles().FirstOrDefault(item => string.Equals(item.Name, name, StringComparison.OrdinalIgnoreCase)) ?? destination.DriveInfo.GetFileInfo(Path.Combine(targetDir.FullName, name)); using (var input = sourceFile.Open(FileMode.Open, FileAccess.Read)) using (var output = targetFile.Open(FileMode.OpenOrCreate, FileAccess.Write)) { input.CopyTo(output); } } foreach (var subSource in source.GetDirectories()) { CopyDirectory(subSource, targetDir); } return(targetDir); }
public async Task FileProcessingWorker_StartAsync_FilesInProgress_FilesMovedAndIsStarted() { IConfigurationRoot configurationRoot = new ConfigurationBuilder().AddInMemoryCollection(TestData.DefaultAppSettings).Build(); ConfigurationReader.Initialise(configurationRoot); this.FileProcessingManager.Setup(f => f.GetAllFileProfiles(It.IsAny <CancellationToken>())) .ReturnsAsync(new List <FileProfile>() { TestData.FileProfileSafaricom }); this.FileSystem.AddDirectory("home/txnproc/bulkfiles/safaricom/inprogress"); this.FileSystem.AddDirectory("home/txnproc/bulkfiles/safaricom/processed"); this.FileSystem.AddDirectory("home/txnproc/bulkfiles/safaricom/failed"); this.FileSystem.AddFile(TestData.InProgressSafaricomFilePathWithName, new MockFileData("D,1,1,1")); CancellationToken c = new CancellationToken(true); // :| Do this to force Execute async to not process the files await this.FileProcessingWorker.StartAsync(c); this.FileProcessingWorker.IsRunning.ShouldBeTrue(); IDirectoryInfo directoryInfo = this.FileSystem.DirectoryInfo.FromDirectoryName("home/txnproc/bulkfiles/safaricom"); directoryInfo.GetFiles("*.*").Length.ShouldBe(1); }
private static FileWithRelativePath[] GetFiles(IDirectoryInfo directory) { return(directory.GetFiles("*.*", SearchOption.AllDirectories) .Select(x => new FileWithRelativePath(x, directory)) .OrderBy(x => x.RelativePath) .ToArray()); }
private void ScanFolderForOldFiles(string folderToScan, DateTime oldestEpisodeToKeep, List <IFileInfo> episodesToDelete, PodcastInfo podcastInfo) { IDirectoryInfo directoryInfo = _directoryInfoProvider.GetDirectoryInfo(folderToScan); IFileInfo[] files; try { files = directoryInfo.GetFiles(podcastInfo.Pattern.Value); } catch (DirectoryNotFoundException) { // if the folder is not there then there is nothing to do return; } foreach (IFileInfo file in files) { var extension = Path.GetExtension(file.FullName); if (extension != null && extension.ToUpperInvariant() == ".XML") { // do not delete the state file continue; } if (GetWhenDownloadWasPublished(podcastInfo, file) < oldestEpisodeToKeep) { episodesToDelete.Add(file); } } }
private static IDirectoryInfo CopyDirectory(IDirectoryInfo source, IDirectoryInfo destination) { var targetDir = destination.GetDirectories().FirstOrDefault(dir => string.Equals(dir.Name, source.Name, StringComparison.OrdinalIgnoreCase)) ?? destination.CreateSubdirectory(source.Name); foreach (var sourceFile in source.GetFiles()) { var name = sourceFile.Name; var targetFile = targetDir.GetFiles().FirstOrDefault(item => string.Equals(item.Name, name, StringComparison.OrdinalIgnoreCase)) ?? destination.DriveInfo.GetFileInfo(Path.Combine(targetDir.FullName, name)); using (var input = sourceFile.Open(FileMode.Open, FileAccess.Read)) using (var output = targetFile.Open(FileMode.OpenOrCreate, FileAccess.Write)) { input.CopyTo(output); } } foreach (var subSource in source.GetDirectories()) { CopyDirectory(subSource, targetDir); } return targetDir; }
public void GetFilesFor2() { string file1 = "file1"; string file2 = "file2"; string fullPath1 = Path.Combine(this.testFolder.FullName, file1); string fullPath2 = Path.Combine(this.testFolder.FullName, file2); var stream = new FileInfo(fullPath1).Create(); stream.Dispose(); var stream2 = new FileInfo(fullPath2).Create(); stream2.Dispose(); IDirectoryInfo dirInfo = Factory.CreateDirectoryInfo(this.testFolder.FullName); Assert.That(dirInfo.GetFiles().Length, Is.EqualTo(2)); Assert.That(dirInfo.GetFiles()[0].Name, Is.EqualTo(file1)); Assert.That(dirInfo.GetFiles()[1].Name, Is.EqualTo(file2)); }
/// <summary> /// This method is called when the <see cref="T:Microsoft.Extensions.Hosting.IHostedService" /> starts. The implementation should return a task that represents /// the lifetime of the long running operation(s) being performed. /// </summary> /// <param name="stoppingToken">Triggered when <see cref="M:Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)" /> is called.</param> /// <returns> /// A <see cref="T:System.Threading.Tasks.Task" /> that represents the long running operations. /// </returns> protected override async Task ExecuteAsync(CancellationToken stoppingToken) { TypeProvider.LoadDomainEventsTypeDynamically(); foreach (KeyValuePair <Type, String> type in TypeMap.Map) { this.LogInformation($"Type name {type.Value} mapped to {type.Key.Name}"); } while (stoppingToken.IsCancellationRequested == false) { try { List <Task> fileProcessingTasks = new List <Task>(); List <FileProfile> fileProfiles = await this.FileProcessorManager.GetAllFileProfiles(stoppingToken); foreach (FileProfile fileProfile in fileProfiles) { this.LogInformation($"About to look in {fileProfile.ListeningDirectory} for files"); IDirectoryInfo listeningDirectory = this.FileSystem.DirectoryInfo.FromDirectoryName(fileProfile.ListeningDirectory); List <IFileInfo> files = listeningDirectory.GetFiles().OrderBy(f => f.CreationTime).Take(1).ToList(); // Only process 1 file per file profile concurrently, foreach (IFileInfo fileInfo in files) { this.LogInformation($"File {fileInfo.Name} detected"); String inProgressFolder = $"{fileProfile.ListeningDirectory}/inprogress/"; if (this.FileSystem.Directory.Exists(inProgressFolder) == false) { throw new DirectoryNotFoundException($"Directory {inProgressFolder} not found"); } String inProgressFilePath = $"{fileProfile.ListeningDirectory}/inprogress/{fileInfo.Name}"; fileInfo.MoveTo(inProgressFilePath, true); IRequest request = this.CreateProcessFileRequest(fileProfile, inProgressFilePath); fileProcessingTasks.Add(this.Mediator.Send(request)); } } await Task.WhenAll(fileProcessingTasks.ToArray()); } catch (Exception e) { this.LogCritical(e); } String fileProfilePollingWindowInSeconds = ConfigurationReader.GetValue("AppSettings", "FileProfilePollingWindowInSeconds"); if (string.IsNullOrEmpty(fileProfilePollingWindowInSeconds)) { fileProfilePollingWindowInSeconds = "60"; } // Delay for configured seconds before polling for files again await Task.Delay(TimeSpan.FromSeconds(int.Parse(fileProfilePollingWindowInSeconds)), stoppingToken); } }
/// <summary> /// returns .zip and .eml files in a given Directory. /// </summary> /// <param name="directoryPath">Directory to extract import files from</param> /// <returns>Array of FileInfo representing all Import-Files</returns> public IFileInfo[] GetImportFiles(string directoryPath) { IDirectoryInfo directory = FileSys.DirectoryInfo.FromDirectoryName(directoryPath); if (!directory.Exists) { throw new DirectoryNotFoundException($"Error-Directory: {directory.FullName} doesn't exist!"); } List <IFileInfo> files = directory.GetFiles("*.eml", SearchOption.TopDirectoryOnly).ToList(); files.AddRange(directory.GetFiles("*.zip", SearchOption.TopDirectoryOnly).ToList()); Log.Logger.Info($"{files.ToArray().Length} Import Files found"); return(files.ToArray()); }
public static void VerifyCharts(ErrorWriter writer, IDirectoryInfo baselineResultInfo, IDirectoryInfo generatedResultInfo) { IFileInfo[] baseFiles = new IFileInfo[0]; if (baselineResultInfo.Exists) { baseFiles = baselineResultInfo.GetFiles("*.jpg"); } IFileInfo[] genFiles = new IFileInfo[0]; if (generatedResultInfo.Exists) { genFiles = generatedResultInfo.GetFiles("*.jpg"); } if (baseFiles.Length < genFiles.Length) { writer.StartError("The new rendering generated too MANY charts:"); foreach (IFileInfo gFile in genFiles) { int foundAt = Array.FindIndex(baseFiles, bFile => string.Equals(bFile.Name, gFile.Name)); if (foundAt == -1) { writer.WriteError("\tAdded: " + gFile); } } writer.EndError(); } else if (baseFiles.Length > genFiles.Length) { writer.StartError("The new rendering generated too FEW charts."); foreach (IFileInfo bFile in baseFiles) { int foundAt = Array.FindIndex(genFiles, gFile => string.Equals(gFile.Name, bFile.Name)); if (foundAt == -1) { writer.WriteError("\tRemoved: " + bFile); } } writer.EndError(); } foreach (IFileInfo baseFI in baseFiles) { IFileInfo genFI = Array.Find(genFiles, gFile => string.Equals(gFile.Name, baseFI.Name)); //due to optimization routines, minor differences occur in the file size of the charts. if (baseFI.Length != genFI.Length && Math.Abs(baseFI.Length - genFI.Length) > 1150) { writer.WriteError( "<strong>Charts do not match:</strong>", "\tExpected length: " + baseFI.Length, "\tGenerated length: " + genFI.Length ); } } }
private IEnumerable <IFileInfo> GetFilesFromDirectory(IDirectoryInfo directory, long lastWriteTimeTicks) { _logger.LogDebug("{ParserName}: Checking directory \"{Directory}\" for files with new data...", Options.ParserName, directory.FullName); var allFiles = directory.GetFiles(); var filesWithNewData = allFiles.Where(f => Regex.IsMatch(f.Name, Options.FileSearchPattern) && f.LastWriteTimeUtc.Ticks > lastWriteTimeTicks); _logger.LogDebug("{ParserName}: Found {FileCount} files with new data in directory \"{Directory}\"", Options.ParserName, filesWithNewData.Count(), directory.FullName); return(filesWithNewData); }
private IMicroserviceDefinition GetMicroserviceDefinition(IDirectoryInfo localization) { var files = localization.GetFiles(_configurationProvider.ProtoPattern); var definitionBuilder = _definitionBuilderFactory.Create(); foreach (var file in files) { definitionBuilder.AddProto(file); } return(definitionBuilder.Build(localization.Name)); }
private static void SetNormalAttribute(IDirectoryInfo dirInfo) { foreach (var subDir in dirInfo.GetDirectories()) { SetNormalAttribute(subDir); } foreach (var file in dirInfo.GetFiles()) { file.Attributes = FileAttributes.Normal; } }
private IEnumerable <IFileInfo> GetFilesFromDirectory(IDirectoryInfo directory, long lastCreatedFileTicks) { _logger.LogDebug("{ParserName}: Checking directory \"{Directory}\" for new files...", Options.ParserName, directory.FullName); var allFiles = directory.GetFiles(); var newFiles = allFiles.Where(f => Regex.IsMatch(f.Name, Options.FileSearchPattern) && f.CreationTimeUtc.Ticks > lastCreatedFileTicks); _logger.LogDebug("{ParserName}: Found {NewFilesCount} files in directory \"{Directory}\"", Options.ParserName, newFiles.Count(), directory.FullName); return(newFiles); }
private void CopyFiles(IDirectoryInfo source, IDirectoryInfo target) { foreach (var fi in source.GetFiles()) { fi.CopyTo(this.fileSystem.Path.Combine(target.FullName, fi.Name)); } foreach (var subDirectory in source.GetDirectories()) { var nextTargetSubDir = target.CreateSubdirectory(subDirectory.Name); this.CopyFiles(subDirectory, nextTargetSubDir); } }
internal static long GetDirectorySize(IDirectoryInfo d) { long ret = 0; foreach (var item in d.GetDirectories()) { ret += GetDirectorySize(item); } foreach (var item in d.GetFiles()) { ret += item.Length; } return(ret); }
private void CopyDirectoryHelper(IDirectoryInfo source, IDirectoryInfo target) { // Check if the target directory exists, if not, create it. if (!target.Exists) { try { Directory.CreateDirectory(target.FullName); } catch (Exception ex) { throw new Exception(string.Format("Failed to create directory: {0}.", target.FullName), ex); } } // Copy each file into its new directory. IFileInfo[] files = source.GetFiles(); foreach (IFileInfo file in files) { // Check if operation was cancelled CheckStopped(); CopyFile(file, new FileInfoWrapper(Path.Combine(target.FullName, file.Name))); } // Copy each subdirectory using recursion. IDirectoryInfo[] subdirectories = source.GetDirectories(); foreach (IDirectoryInfo sourceSubdirectory in subdirectories) { // Check if operation was cancelled CheckStopped(); IDirectoryInfo targetSubdirectory = new DirectoryInfoWrapper(Path.Combine(target.FullName, sourceSubdirectory.Name)); if (!targetSubdirectory.Exists) { try { targetSubdirectory.Create(); } catch (Exception ex) { throw new Exception( string.Format("Failed to create directory: {0}.", targetSubdirectory.FullName), ex); } } CopyDirectoryHelper(sourceSubdirectory, targetSubdirectory); } target.Attributes = source.Attributes; target.LastWriteTime = source.LastWriteTime; }
private IEnumerable <IFileInfo> GetSortedFiles(IDirectoryInfo src, string pattern, PodcastFileSortField sortField, bool ascendingSort) { try { var fileList = new Collection <IFileInfo>(src.GetFiles(pattern)); return(FileSorter.Sort(fileList, sortField, ascendingSort)); } catch (DirectoryNotFoundException) { // if the folder is not there then there is nothing to do return(new Collection <IFileInfo>()); } }
// ****************************************************************************** /// <summary> /// Returns a fully populate heirarchy for this forlder /// </summary> /// <param name="directoryInfo">Object representing the root folder to scan</param> /// <returns>Populated Heirarchy</returns> // ****************************************************************************** CosmosDirItem ScanFolder(IDirectoryInfo directoryInfo, CancellationToken cancelToken) { CurrentItemLabel = directoryInfo.FullName; CosmosDirectoryInfo cosmosDirectoryInfo = (CosmosDirectoryInfo)directoryInfo; CosmosDirItem thisDir = new CosmosDirItem(directoryInfo.Name, directoryInfo.FullName); //thisDir.TotalValue = Math.Max(0, cosmosDirectoryInfo.CosmosSize); if (cancelToken.IsCancellationRequested) { return(thisDir); } double totalFolderSize = 0; try { // Total up the size of the content foreach (var file in directoryInfo.GetFiles()) { thisDir.AddContent(file.Name, file); var fileSize = Math.Max(0, file.GetValue(CosmosDirectoryInfo.STREAMSIZE)); UnitsScannedSoFar += fileSize; totalFolderSize += fileSize; file.SetValue(CosmosDirectoryInfo.STREAMSIZE, fileSize); if (cancelToken.IsCancellationRequested) { return(thisDir); } } // recurse into the child directories foreach (IDirectoryInfo dir in directoryInfo.GetDirectories()) { CosmosDirItem newDir = ScanFolder(dir, cancelToken); thisDir.AddChild(newDir); } } catch (UnauthorizedAccessException) { } // Ignore permissions problems catch (Exception e) { #if DEBUG Debugger.Break(); #endif Debug.WriteLine("Error: " + e.Message); } //thisDir.TotalValue = totalFolderSize; return(thisDir); }
/// <summary> /// remove a folder if there are no files in it, used by the synchroniser /// </summary> /// <param name="folder">folder to delete</param> /// <param name="whatIf">true to emit all the status updates but not actually perform the deletes, false to do the delete</param> public void RemoveFolderIfEmpty(string folder, bool whatIf) { IDirectoryInfo directoryInfo = _directoryInfoProvider.GetDirectoryInfo(folder); if (!directoryInfo.Exists) { return; } IDirectoryInfo[] subFolders; try { subFolders = directoryInfo.GetDirectories("*.*"); } catch (DirectoryNotFoundException) { // if the folder is not there then there is nothing to do return; } if (subFolders != null && subFolders.Length > 0) { // the folder is not empty - there are subfolders return; } IFileInfo[] files; try { files = directoryInfo.GetFiles("*.*"); } catch (DirectoryNotFoundException) { // if the folder is not there then there is nothing to do return; } if (files != null && files.Length > 0) { // the folder is not empty there are files return; } OnStatusUpdate(string.Format(CultureInfo.InvariantCulture, "Removing folder: {0}", directoryInfo.FullName)); if (!whatIf) { directoryInfo.Delete(); } }
private void CopyAll(IDirectoryInfo source, IDirectoryInfo destination) { // copy each file into destination foreach (var file in source.GetFiles()) { file.CopyTo(_fileSystem.Path.Combine(destination.FullName, file.Name), true); } // copy each subdirectory using recursion foreach (var diSourceSubDir in source.GetDirectories()) { var nextTargetSubDir = destination.CreateSubdirectory(diSourceSubDir.Name); CopyAll(diSourceSubDir, nextTargetSubDir); } }
public DisplayComponentModel(IDirectoryInfo installerRootDirectory, IDirectoryInfo componentDirectory) { StaticViewModel.AddDebugMessage($"Found display component in {componentDirectory.FullName}"); Keep = true; _componentDirectory = componentDirectory; Directory = componentDirectory.FullName.Substring(componentDirectory.FullName.IndexOf(installerRootDirectory.FullName) + installerRootDirectory.FullName.Length); IFileInfo[] infFiles = componentDirectory.GetFiles("*.inf", SearchOption.TopDirectoryOnly); if (infFiles.Length > 0) { InfFile = infFiles[0].Name; LoadInfFileInformation(infFiles[0]); } }
public void Init(IDirectoryInfo d) { if (StartDirectory == null) { StartDirectory = d; } Sectors.Clear(); Text = "Memory report: " + d.FullName; CurrentDirectory = d; var list = Stuff.GetAllFiles(d); var total = list.Sum(z => z.Length); TotalLen = total; var rootl = d.GetFiles().Sum(z => z.Length); if (rootl > 0) { Sectors.Add(new ReportSectorInfo() { Name = ".root", Length = rootl, Tag = d, Percentage = (float)rootl / total }); } foreach (var item in d.GetDirectories()) { var f = Stuff.GetAllFiles(item); var l = f.Sum(z => z.Length); Sectors.Add(new ReportSectorInfo() { Name = item.Name, Length = l, Percentage = (float)l / total, Tag = item }); } Sectors = Sectors.OrderByDescending(z => z.Percentage).ToList(); listView1.Items.Clear(); foreach (var item in Sectors) { listView1.Items.Add(new ListViewItem(new string[] { item.Name, Stuff.GetUserFriendlyFileSize(item.Length), (item.Percentage * 100).ToString("F") + "%" }) { Tag = item }); } //listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); //listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); }
/// <exception cref="FileEntityNotFoundException">Ошибка при получении списка файлов</exception> public override List <FileSystemEntity> GetFiles() { IFileInfo[] files; try { files = info.GetFiles(); } catch (DirectoryNotFoundException e) { throw new FileEntityNotFoundException("Ошибка при получении списка файлов.", e); } var result = new List <FileSystemEntity>(); for (var i = 0; i < files.Length; ++i) { result.Add(new FileEntity(files[i])); } return(result); }
private void commandDirectorySearch(Dictionary <string, object> arguments) { bool shouldDelete = arguments.ContainsKey("--delete"); bool noRecursive = arguments.ContainsKey("--norecursive"); string fileNamePattern = (string)arguments["FileNamePattern"]; IDirectoryInfo directoryToSearch = (IDirectoryInfo)arguments["DirectoryToSearch"]; if (!directoryToSearch.Exists) { throw new CommandLineArgumentException("<DirectoryToSearch>", "Directory does not exist."); } System.IO.SearchOption searchOption = noRecursive ? System.IO.SearchOption.TopDirectoryOnly : System.IO.SearchOption.AllDirectories; IFileInfo[] foundFiles = directoryToSearch.GetFiles(fileNamePattern, searchOption); foreach (IFileInfo file in foundFiles) { string relativePath = file.GetRelativePath(directoryToSearch); this.log(relativePath); } this.log($"Found {foundFiles.Length} files matching '{fileNamePattern}' in '{directoryToSearch.FullName}'."); if (shouldDelete && foundFiles.Any()) { this.outputWriter.WriteLine($"Really delete? <yes|no>"); if (!string.Equals(this.inputReader.ReadLine(), "yes", StringComparison.OrdinalIgnoreCase)) { throw new OperationCanceledException("Aborting, nothing deleted."); } int deletedCount = 0; try { foreach (IFileInfo file in foundFiles) { file.Delete(); deletedCount++; } } finally { this.log($"Deleted {deletedCount} files."); } } }
private void When_getting_files_it_must_succeed() { // Arrange const string path = @"c:\some\folder"; IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingEmptyFile(@"c:\some\folder\file.txt") .Build(); IDirectoryInfo dirInfo = fileSystem.ConstructDirectoryInfo(path); // Act IFileInfo[] infos = dirInfo.GetFiles(); // Assert infos.Should().ContainSingle(x => x.FullName == @"c:\some\folder\file.txt"); }
/// <summary> /// Gets the local directory tree. /// </summary> /// <returns>The local directory tree.</returns> /// <param name="parent">Parent directory.</param> /// <param name="filter">Filter for files.</param> public static IObjectTree <IFileSystemInfo> GetLocalDirectoryTree(IDirectoryInfo parent, IFilterAggregator filter) { var children = new List <IObjectTree <IFileSystemInfo> >(); try { foreach (var child in parent.GetDirectories()) { string reason; if (!filter.InvalidFolderNamesFilter.CheckFolderName(child.Name, out reason) && !filter.FolderNamesFilter.CheckFolderName(child.Name, out reason) && !filter.SymlinkFilter.IsSymlink(child, out reason)) { children.Add(GetLocalDirectoryTree(child, filter)); } else { Logger.Info(reason); } } foreach (var file in parent.GetFiles()) { string reason; if (!filter.FileNamesFilter.CheckFile(file.Name, out reason) && !filter.SymlinkFilter.IsSymlink(file, out reason)) { children.Add(new ObjectTree <IFileSystemInfo> { Item = file, Children = new List <IObjectTree <IFileSystemInfo> >() }); } else { Logger.Info(reason); } } } catch (System.IO.PathTooLongException) { Logger.Fatal(string.Format("One or more children paths of \"{0}\" are to long to be synchronized, synchronization is impossible since the problem is fixed", parent.FullName)); throw; } IObjectTree <IFileSystemInfo> tree = new ObjectTree <IFileSystemInfo> { Item = parent, Children = children }; return(tree); }
public bool BuildBaseProject(ProjectInstallInfo installedProjectInfo, IDirectoryInfo projectBackupDir, string baseProjectPath) { if (!projectBackupDir.Exists) throw new ArgumentException("Path does not exist.", "projectBackupPath"); if (string.IsNullOrEmpty(installedProjectInfo.ProjectVersionInfo.BackupFileName)) throw new ArgumentException("BackupFileName is not set.", "projectInfo"); IFileInfo backupFile = projectBackupDir.GetFiles(installedProjectInfo.ProjectVersionInfo.BackupFileName).FirstOrDefault(); if (backupFile == null) { throw new ApplicationException(string.Format("Project backup file {0} does not exist.", Path.Combine(projectBackupDir.FullName, installedProjectInfo.ProjectVersionInfo.BackupFileName))); } IDirectoryInfo baseDir = FileSystem.FileSystem.GetDirectoryInfo(baseProjectPath); if (!baseDir.Exists) baseDir.Create(); var bundlesToInstall = installedProjectInfo.BundlesApplied .OrderBy(b => b.Version.Major) .ThenBy(b => b.Version.Minor) .ThenBy(b => b.Version.Build) .ThenBy(b => b.Version.Revision); //ensure we can find all the bundle files foreach (BundleInfo bundleInfo in bundlesToInstall) { if (!BundleExistsInRepository(projectBackupDir, bundleInfo.FileName)) { _log.Error(string.Format("The bundle file \"{0}\" could not be found.", bundleInfo.FileName)); Environment.Exit(-1); } } var backup = new ProjectBackup(backupFile.FullName); var workspace = new ProjectWorkspace(baseProjectPath); workspace.RestoreProjectFromBackup(backup); IProject project = new Project(workspace); var pcs = new SimpleProjectContextService(project); ApplicationContext.Current.Services.Add(typeof(IProjectContextService), pcs); var installResults = bundlesToInstall.Select(bundleInfo => InstallBundle(projectBackupDir.FullName, bundleInfo.FileName, project)); return installResults.All(result => result); }
private bool BundleExistsInRepository(IDirectoryInfo bundleDir, string bundleFileName) { IFileInfo bundleFile = bundleDir.GetFiles(bundleFileName).FirstOrDefault(); if (bundleFile == null) return false; return bundleFile.Exists; }
/// <summary> /// Gets the local directory tree. /// </summary> /// <returns>The local directory tree.</returns> /// <param name="parent">Parent directory.</param> /// <param name="filter">Filter for files.</param> public static IObjectTree<IFileSystemInfo> GetLocalDirectoryTree(IDirectoryInfo parent, IFilterAggregator filter) { var children = new List<IObjectTree<IFileSystemInfo>>(); try { foreach (var child in parent.GetDirectories()) { string reason; if (!filter.InvalidFolderNamesFilter.CheckFolderName(child.Name, out reason) && !filter.FolderNamesFilter.CheckFolderName(child.Name, out reason) && !filter.SymlinkFilter.IsSymlink(child, out reason)) { children.Add(GetLocalDirectoryTree(child, filter)); } else { Logger.Info(reason); } } foreach (var file in parent.GetFiles()) { string reason; if (!filter.FileNamesFilter.CheckFile(file.Name, out reason) && !filter.SymlinkFilter.IsSymlink(file, out reason)) { children.Add(new ObjectTree<IFileSystemInfo> { Item = file, Children = new List<IObjectTree<IFileSystemInfo>>() }); } else { Logger.Info(reason); } } } catch (System.IO.PathTooLongException) { Logger.Fatal(string.Format("One or more children paths of \"{0}\" are to long to be synchronized, synchronization is impossible since the problem is fixed", parent.FullName)); throw; } IObjectTree<IFileSystemInfo> tree = new ObjectTree<IFileSystemInfo> { Item = parent, Children = children }; return tree; }
/// <summary> /// Processes the specified directory looking for episodes. /// </summary> /// <param name="directory"> /// The directory to search. /// </param> /// <param name="overrideRecurse"> /// A value indicating whether the setting for recurse subdirectories should be overriden. /// </param> /// <param name="ignoreShowUpdate"> /// A value indicating whether the settings for updating and locked shows should be ignored. /// </param> /// <returns> /// The list of identified files. /// </returns> private IEnumerable<FileResult> ProcessDirectory( IDirectoryInfo directory, bool overrideRecurse = false, bool ignoreShowUpdate = false) { // Get the files where the extension is in the list of extensions. IEnumerable<IFileInfo> files = directory.GetFiles().Where(file => this.settings.FileExtensions.Contains(file.Extension)); foreach (FileResult result in files.Select(info => this.ProcessFile(info, ignoreShowUpdate))) { if (result != null) { yield return result; } } // If ignore show update is on then this is being run from the FileManger as part // of a move or copy operation. It should add to log that it is scanning the directory. if (!ignoreShowUpdate) { Logger.OnLogMessage(this, "Scanned directory: {0}", LogType.Info, directory.FullName.Truncate()); } if (!this.settings.RecurseSubdirectories && !overrideRecurse) { yield break; } IDirectoryInfo[] dirs = directory.GetDirectories().Where(d => !d.DirectoryAttributes.HasFlag(FileAttributes.System) && !settings.IgnoredDirectories.Contains(d.FullName)).ToArray(); foreach (FileResult result in dirs.SelectMany(dir => this.ProcessDirectory(dir, overrideRecurse, ignoreShowUpdate))) { yield return result; } }
/// <summary> /// Creates a test file with the specified name under the TV directory. /// </summary> /// <param name="directory"> /// The directory that the file is in. /// </param> /// <param name="names"> /// The names of the files to create. /// </param> /// <returns> /// The files that have been created. /// </returns> protected IFileInfo[] CreateTestFile(IDirectoryInfo directory, params string[] names) { var files = new IFileInfo[names.Length]; for (int i = 0; i < names.Length; i++) { var file = Substitute.For<IFileInfo>(); file.Name.Returns(names[i]); string fullName = string.Concat(directory.FullName, Path.DirectorySeparatorChar, names[i]); file.FullName.Returns(fullName); file.Extension.Returns(names[i].Substring(names[i].LastIndexOf('.'))); file.Exists.Returns(true); file.Directory.Returns(directory); files[i] = file; } directory.GetFiles().Returns(files); return files; }
bool doesFolderContainCssFiles(IDirectoryInfo di) { if (di.FullName.Contains("\\App_Themes\\Default\\WAF\\")) return false; if (di.GetFiles("*.css").Length > 0) return true; foreach (var sdi in di.GetDirectories()) { if (doesFolderContainCssFiles(sdi)) return true; } return false; }
internal void AddDirectoryFilesToRepository(IDirectoryInfo directory, Version version, int? bundleId = null, int? projectId = null) { IFileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories); var totalFiles = files.Length; if (totalFiles == 0) return; using (var connection = GetOpenConnection()) { IDbTransaction trans = null; for (int i = 0; i < totalFiles; i++) { if (trans == null) trans = connection.BeginTransaction(); if (FileShouldBeTracked(files[i].Url)) AddFileToReleaseDb(files[i], version, connection, bundleId, projectId); if (i % 100 == 0) { trans.Commit(); trans.Dispose(); trans = null; } //notify progress every 100 files if ((i % 100 == 0) && (AddFileProgress != null)) { var percentComplete = (int)((i / (float)totalFiles) * 100); AddFileProgress(this, new FileProgressEventArgs(percentComplete)); } } if (trans != null) { trans.Commit(); trans.Dispose(); } if (AddFileProgress != null) AddFileProgress(this, new FileProgressEventArgs(100)); } }
/// <summary> /// Scans a directory recursively. /// </summary> /// <param name="rootDirectory">The root directory.</param> private void ScanDirectories(IDirectoryInfo rootDirectory) { if (this.IsStopped) { return; } try { if (rootDirectory.Exists) { IEnumerable<IFileInfo> files = rootDirectory.GetFiles(); foreach (IFileInfo file in files) { if (this.IsStopped) { return; } if (file.Exists) { this.OnFileFound(new FileFoundEventArgs(file)); } } IEnumerable<IDirectoryInfo> directories = rootDirectory.GetDirectories(); foreach (IDirectoryInfo directory in directories) { if (this.IsStopped) { return; } if (directory.Name == "$RECYCLE.BIN" || !directory.Exists) { continue; } this.OnDirectoryFound(new DirectoryFoundEventArgs(directory)); this.ScanDirectories(directory); } } } // Catch the exceptions and don't handle anything, // we want to skip those files or directories catch (UnauthorizedAccessException) { } catch (SecurityException) { } catch (IOException) { } this.OnDirectoryProceeded(EventArgs.Empty); }
bool doesFolderContainAspxFiles(IDirectoryInfo di) { if (di.GetFiles("*.aspx").Length > 0) return true; foreach (var sdi in di.GetDirectories()) { if (doesFolderContainAspxFiles(sdi)) return true; } return false; }
private void AddDirectoryToZipFile (IDirectoryInfo directoryInfo, ZipOutputStream zipOutputStream, ZipNameTransform nameTransform) { foreach (var file in directoryInfo.GetFiles ()) AddFileToZipFile (file, zipOutputStream, nameTransform); foreach (var directory in directoryInfo.GetDirectories ()) AddDirectoryToZipFile (directory, zipOutputStream, nameTransform); }
bool doesFolderContainAspxFiles(IDirectoryInfo di, int callLevel) { if (di.Name.ToLower() == "node_modules") return false; if (callLevel > 6) return false; try { if (di.GetFiles("*.aspx").Length > 0) return true; foreach (var sdi in di.GetDirectories()) { if (doesFolderContainAspxFiles(sdi, callLevel + 1)) return true; } } catch (PathTooLongException) { } return false; }
///// <summary> ///// Deletes the subdirectories of the file if they are empty. ///// </summary> ///// <param name="file"> ///// The file to check. ///// </param> //private void DeleteEmptySubdirectories(FileResult file) //{ // // If no files exist in the directory // if (file.InputFile.Directory != null && !file.InputFile.Directory.GetFiles().Any() // && !file.InputFile.Directory.GetDirectories().Any()) // { // // If this isn't the source directory // if ( // !file.InputFile.Directory.FullName.TrimEnd(Path.DirectorySeparatorChar).Equals( // this.settings.SourceDirectory.TrimEnd(Path.DirectorySeparatorChar))) // { // file.InputFile.Directory.Delete(true); // Logger.OnLogMessage(this, "Delete directory: {0}", LogType.Info, file.InputFile.DirectoryName.Truncate()); // } // } //} /// <summary> /// Deletes the Empty source folder after copy /// </summary> /// <param name="directory">Directory to delete</param> private void DeleteEmptySubdirectories(IDirectoryInfo directory) { if(directory != null && !directory.GetFiles().Where(file => this.settings.FileExtensions.Contains(file.Extension)).Any()) { if (!directory.FullName.ToLower().Equals(this.settings.DefaultDestinationDirectory)) { directory.Delete(true); Logger.OnLogMessage(this, "Delete directory: {0}", LogType.Info, directory.FullName.Truncate()); } } }