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 LibraryFileInfo(ISDataClient client, bool formMode, IDirectoryInfo directory, LibraryDocument document) : base(directory) { _client = client; _formMode = formMode; _document = document; }
/// <summary> /// Initializes a new instance of the <see cref="CmisSync.Lib.Producer.Crawler.DescendantsTreeBuilder"/> class. /// </summary> /// <param name='storage'> /// The MetadataStorage. /// </param> /// <param name='remoteFolder'> /// Remote folder. /// </param> /// <param name='localFolder'> /// Local folder. /// </param> /// <param name='filter'> /// Aggregated Filters. /// </param> /// <exception cref='ArgumentNullException'> /// <attribution license="cc4" from="Microsoft" modified="false" /><para>The exception that is thrown when a /// null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument. </para> /// </exception> public DescendantsTreeBuilder( IMetaDataStorage storage, IFolder remoteFolder, IDirectoryInfo localFolder, IFilterAggregator filter, IIgnoredEntitiesStorage ignoredStorage) { if (remoteFolder == null) { throw new ArgumentNullException("remoteFolder"); } if (localFolder == null) { throw new ArgumentNullException("localFolder"); } if (storage == null) { throw new ArgumentNullException("storage"); } if (filter == null) { throw new ArgumentNullException("filter"); } if (ignoredStorage == null) { throw new ArgumentNullException("ignoredStorage"); } this.storage = storage; this.remoteFolder = remoteFolder; this.localFolder = localFolder; this.filter = filter; this.matcher = new PathMatcher(localFolder.FullName, remoteFolder.Path); this.ignoredStorage = ignoredStorage; }
/// <summary> /// Creates the specified directory in the target directory. /// </summary> /// <param name="sourceDirectory">The source directory.</param> /// <param name="targetDirectory">The target directory.</param> /// <exception cref="AccessException">The directory could not be accessed.</exception> public void CreateDirectory(IDirectoryInfo sourceDirectory, IDirectoryInfo targetDirectory) { sourceDirectory.ThrowIfNull(() => sourceDirectory); targetDirectory.ThrowIfNull(() => targetDirectory); try { Directory.CreateDirectory(this.CombinePath(targetDirectory.FullName, sourceDirectory.Name)); } catch (DirectoryNotFoundException ex) { throw new AccessException("The file could not be accessed.", ex); } catch (PathTooLongException ex) { throw new AccessException("The file could not be accessed.", ex); } catch (IOException ex) { throw new AccessException("The file could not be accessed.", ex); } catch (UnauthorizedAccessException ex) { throw new AccessException(ex.Message, ex); } }
/// <summary> /// Initializes a new instance of the <see cref="DescendantsCrawler"/> class. /// </summary> /// <param name="queue">Sync Event Queue.</param> /// <param name="remoteFolder">Remote folder.</param> /// <param name="localFolder">Local folder.</param> /// <param name="storage">Meta data storage.</param> /// <param name="filter">Aggregated filter.</param> /// <param name="activityListener">Activity listner.</param> public DescendantsCrawler( ISyncEventQueue queue, IFolder remoteFolder, IDirectoryInfo localFolder, IMetaDataStorage storage, IFilterAggregator filter, IActivityListener activityListener, IIgnoredEntitiesStorage ignoredStorage) : base(queue) { if (remoteFolder == null) { throw new ArgumentNullException("remoteFolder"); } if (localFolder == null) { throw new ArgumentNullException("localFolder"); } if (storage == null) { throw new ArgumentNullException("storage"); } if (filter == null) { throw new ArgumentNullException("filter"); } if (activityListener == null) { throw new ArgumentNullException("activityListener"); } this.activityListener = activityListener; this.treebuilder = new DescendantsTreeBuilder(storage, remoteFolder, localFolder, filter, ignoredStorage); this.eventGenerator = new CrawlEventGenerator(storage); this.notifier = new CrawlEventNotifier(queue); }
public AttachmentFileInfo(ISDataClient client, bool formMode, IDirectoryInfo directory, Attachment attachment) : base(directory) { _client = client; _formMode = formMode; _attachment = attachment; }
public bool TryToCreateDirectory(IDirectoryInfo directory) { if (directory.Exists) return false; directory.Create(); return true; }
public RarFileInfo(IDirectoryInfo parentDir, string rarPath, Schematrix.RARFileInfo rarFileInfo) { _parentDir = parentDir; _rarPath = rarPath; //The rar archive file path _lastModifiedTime = rarFileInfo.FileTime; _size = rarFileInfo.UnpackedSize; _filePath = rarFileInfo.FileName; //Path of the file within the rar archive }
public ZipFileInfo(IDirectoryInfo parentDir, string zipPath, ZipEntry entry) { _parentDir = parentDir; _zipPath = zipPath; _fullPath = entry.Name; _lastModifiedTime = entry.DateTime; _size = entry.Size; }
/// <summary> /// Initializes a new instance of the <see cref="FileCopyErrorEventArgs"/> class. /// </summary> /// <param name="file">The file.</param> /// <param name="targetDirectory">The target directory.</param> public FileCopyErrorEventArgs(IFileInfo file, IDirectoryInfo targetDirectory) { file.ThrowIfNull(() => file); targetDirectory.ThrowIfNull(() => targetDirectory); this.File = file; this.TargetDirectory = targetDirectory; }
/// <summary> /// Initializes a new instance of the <see cref="CmisSync.Lib.Events.CrawlRequestEvent"/> class. /// </summary> /// <param name='localFolder'> /// Local folder. /// </param> /// <param name='remoteFolder'> /// Remote folder. /// </param> public CrawlRequestEvent(IDirectoryInfo localFolder, IFolder remoteFolder) { if (localFolder == null) { throw new ArgumentNullException("localFolder"); } this.RemoteFolder = remoteFolder; this.LocalFolder = localFolder; }
/// <summary> /// Initializes a new instance of the <see cref="DirectoryCreationEventArgs"/> class. /// </summary> /// <param name="directory">The directory.</param> /// <param name="targetDirectory">The target directory.</param> public DirectoryCreationEventArgs(IDirectoryInfo directory, IDirectoryInfo targetDirectory) { directory.ThrowIfNull(() => directory); targetDirectory.ThrowIfNull(() => targetDirectory); this.Directory = directory; this.TargetDirectory = targetDirectory; }
public void SetUp () { _directoryName = "Parent\\Directory"; _parentDirectory = MockRepository.GenerateStub<IDirectoryInfo>(); _creationTime = new DateTime (2009, 10, 1); _lastAccessTime = new DateTime (2009, 10, 2); _lastWriteTime = new DateTime (2009, 10, 3); _inMemoryDirectoryInfo = new InMemoryDirectoryInfo (_directoryName, _parentDirectory, _creationTime, _lastAccessTime, _lastWriteTime); }
/// <summary> /// Initializes a new instance of the <see cref="CmisSync.Lib.Events.FolderEvent"/> class. /// </summary> /// <param name="localFolder">Local folder.</param> /// <param name="remoteFolder">Remote folder.</param> /// <param name="src">Event creator.</param> public FolderEvent(IDirectoryInfo localFolder = null, IFolder remoteFolder = null, object src = null) { if (localFolder == null && remoteFolder == null) { throw new ArgumentNullException("One of the given folders must not be null"); } this.LocalFolder = localFolder; this.RemoteFolder = remoteFolder; this.Source = src; }
/// <summary> /// Initializes a new instance of the <see cref="FileSystemScanner"/> class. /// </summary> /// <param name="rootDirectory">The root directory.</param> /// <exception cref="System.ArgumentException"> /// The exception that is thrown, if the root directory doesn't exists /// </exception> public FileSystemScanner(IDirectoryInfo rootDirectory) { rootDirectory.ThrowIfNull(() => rootDirectory); if (!rootDirectory.Exists) throw new ArgumentException("The root directory must exist!"); this.rootDirectory = rootDirectory; }
public AvatarService(IPathResolver pathResolver, IFileSystem fileSystemProvider) { _pathResolver = pathResolver; _fileSystemProvider = fileSystemProvider; _avatarDirectoryInfo = _fileSystemProvider.GetDirectory("avatars"); if (!_avatarDirectoryInfo.Exists) _avatarDirectoryInfo.Create(); }
/// <summary> /// Initializes a new instance of the <see cref="CmisSync.Lib.Events.FolderMovedEvent"/> class. /// </summary> /// <param name="oldLocalFolder">Old local folder.</param> /// <param name="newLocalFolder">New local folder.</param> /// <param name="oldRemoteFolderPath">Old remote folder path.</param> /// <param name="newRemoteFolder">New remote folder.</param> /// <param name="src">Creator of the event.</param> public FolderMovedEvent( IDirectoryInfo oldLocalFolder, IDirectoryInfo newLocalFolder, string oldRemoteFolderPath, IFolder newRemoteFolder, object src = null) : base(newLocalFolder, newRemoteFolder, src) { this.OldLocalFolder = oldLocalFolder; this.OldRemoteFolderPath = oldRemoteFolderPath; }
public SevenZipFileInfo(IDirectoryInfo parentDir, string sevenZipPath, uint fileIndex, FileItem fileItem) { _parentDir = parentDir; _sevenZipPath = sevenZipPath; _fileIndex = fileIndex; _fileItem = fileItem; _fullPath = fileItem.Name.Replace("\0", ""); _size = (long)fileItem.Size; }
public RepositoryRootDeletedDetection(IDirectoryInfo localRootPath) { if (localRootPath == null) { throw new ArgumentNullException(); } this.path = localRootPath; this.absolutePath = this.path.FullName; this.isRootFolderAvailable = this.IsRootFolderAvailable(); }
public ExtractedZipEntryAsFileInfo (ZipFile zipFile, ZipEntry zipEntry, IDirectoryInfo directory) { ArgumentUtility.CheckNotNull ("zipFile", zipFile); ArgumentUtility.CheckNotNull ("zipEntry", zipEntry); _zipFile = zipFile; _zipEntry = zipEntry; _directory = directory; }
/// <summary> /// Gets the directories of the original instance wrapped by new DirectoryInfoWrapper instances. /// </summary> /// <returns>The directories.</returns> public IDirectoryInfo[] GetDirectories() { DirectoryInfo[] originalDirs = this.original.GetDirectories(); IDirectoryInfo[] wrappedDirs = new IDirectoryInfo[originalDirs.Length]; for (int i = 0; i < originalDirs.Length; i++) { wrappedDirs[i] = new DirectoryInfoWrapper(originalDirs[i]); } return wrappedDirs; }
/// <summary> /// Initializes a new instance of the <see cref="FileCopyEventArgs"/> class. /// </summary> /// <param name="file">The file.</param> /// <param name="sourceDirectory">The source directory.</param> /// <param name="targetDirectory">The target directory.</param> public FileCopyEventArgs(IFileInfo file, IDirectoryInfo sourceDirectory, IDirectoryInfo targetDirectory) { file.ThrowIfNull(() => file); sourceDirectory.ThrowIfNull(() => sourceDirectory); targetDirectory.ThrowIfNull(() => targetDirectory); this.File = file; this.SourceDirectory = sourceDirectory; this.TargetDirectory = targetDirectory; }
private void RemoveDyfFiles(IEnumerable<string> filePaths, IDirectoryInfo dyfDir) { var dyfsToRemove = filePaths .Where(x => x.EndsWith(".dyf") && fileSystem.FileExists(x) && Path.GetDirectoryName(x) != dyfDir.FullName); foreach (var dyf in dyfsToRemove) { fileSystem.DeleteFile(dyf); } }
public void AddDirectoryInfo(IDirectoryInfo dirInfo) { //Remove old directoryInfo, if back button has been clicked while (_dirInfoHistory.Count > (_currIndex + 1)) _dirInfoHistory.RemoveAt(_dirInfoHistory.Count - 1); //Add directoryInfo _currIndex = _dirInfoHistory.Count; _dirInfoHistory.Add(dirInfo); UpdateButtonStatus(); }
public void SetUp () { _fileName= "Directory\\File.ext"; _stream = new MemoryStream(new byte[10]); _directory = MockRepository.GenerateStub<IDirectoryInfo>(); _creationTime = new DateTime (2009, 10, 1); _lastAccessTime = new DateTime (2009, 10, 2); _lastWriteTime = new DateTime (2009, 10, 3); _inMemoryFileInfo = new InMemoryFileInfo (_fileName, _stream, _directory, _creationTime, _lastAccessTime, _lastWriteTime); }
/// <summary> /// Copies the specified file to the target directory. /// </summary> /// <param name="sourceFileSystem">The source file system.</param> /// <param name="sourceFile">The source file.</param> /// <param name="targetDirectory">The target directory.</param> /// <exception cref="AccessException">The source file or target directory could not be accessed.</exception> public void CopyFile(IFileSystem sourceFileSystem, IFileInfo sourceFile, IDirectoryInfo targetDirectory) { sourceFileSystem.ThrowIfNull(() => sourceFileSystem); sourceFile.ThrowIfNull(() => sourceFile); targetDirectory.ThrowIfNull(() => targetDirectory); if (!(targetDirectory is LocalDirectoryInfo)) throw new ArgumentException("The target directory must be of type LocalDirectoryInfo.", "targetDirectory"); try { using (Stream sourceStream = sourceFileSystem.OpenFileStream(sourceFile)) { string targetFilePath = this.CombinePath(targetDirectory.FullName, sourceFile.Name); try { using (FileStream targetStream = File.Create(targetFilePath)) { if (sourceFile.Length > 0) { var copyOperation = new StreamCopyOperation(sourceStream, targetStream, 256 * 1024, true); copyOperation.CopyProgressChanged += (sender, e) => this.FileCopyProgressChanged.RaiseSafe(this, e); copyOperation.Execute(); } } } catch (IOException) { File.Delete(targetFilePath); throw; } } } catch (UnauthorizedAccessException ex) { throw new AccessException("The file could not be accessed.", ex); } catch (SecurityException ex) { throw new AccessException("The file could not be accessed.", ex); } catch (IOException ex) { throw new AccessException("The file could not be accessed.", ex); } }
public IFileInfo Zip(IDirectoryInfo directory) { if (directory == null) throw new ArgumentNullException("directory"); if (!(new MutatingFileSystem()).DirectoryExists(directory.FullName)) { throw new DirectoryNotFoundException(directory.FullName); } return new RealFileInfo(Greg.Utility.FileUtilities.Zip(directory.FullName)); }
public RarDirectoryInfo(BaseFileInfo fileInfo) { _rarPath = fileInfo.FullPath; _parentDir = fileInfo.Directory; _lastModifiedTime = fileInfo.LastModifiedTime; foreach (Schematrix.RARFileInfo rarFInfo in UnrarReader.GetFiles(_rarPath)) _fileInfoList.Add(new RarFileInfo(this, _rarPath, rarFInfo)); //TODO Directory support }
public InMemoryFileInfo (string fileName, Stream stream, IDirectoryInfo directory, DateTime creationTimeUtc, DateTime lastAccessTimeUtc, DateTime lastWriteTimeUtc) { ArgumentUtility.CheckNotNullOrEmpty ("fileName", fileName); ArgumentUtility.CheckNotNull ("stream", stream); _fileName = fileName; _stream = stream; _creationTimeUtc = creationTimeUtc; _lastAccessTimeUtc = lastAccessTimeUtc; _lastWriteTimeUtc = lastWriteTimeUtc; _directory = directory; }
public MigrationModel(IProject project) : base(project) { Guard.ArgumentNotNull(project, "project"); _reportInfo = new ModelItemInfo(this, typeof (MigrationReport)); _modelRoot = Project.Drive.GetDirectoryInfo(ModelRootPath); if (!_modelRoot.Exists) { _modelRoot.Create(); } }
private void CreateFolderIfNeeded() { string folder = Path.GetDirectoryName(_syncItem.DestinationPath); IDirectoryInfo dir = _directoryInfoProvider.GetDirectoryInfo(folder); if (!dir.Exists) { dir.Create(); } if (_fileUtilities.FileExists(_syncItem.DestinationPath)) { _fileUtilities.FileDelete(_syncItem.DestinationPath); } }
private void When_constructing_file_info_for_existing_local_file_with_different_casing_it_must_succeed() { // Arrange const string path = @"c:\SOME\file.TXT"; DateTime creationTimeUtc = 17.March(2006).At(14, 03, 53).AsUtc(); var clock = new SystemClock(() => creationTimeUtc); IFileSystem fileSystem = new FakeFileSystemBuilder(clock) .IncludingEmptyFile(@"C:\some\FILE.txt") .Build(); DateTime lastWriteTimeUtc = 18.March(2006).At(14, 03, 53).AsUtc(); clock.UtcNow = () => lastWriteTimeUtc; fileSystem.File.WriteAllText(path, DefaultContents); DateTime lastAccessTimeUtc = 19.March(2006).At(14, 03, 53).AsUtc(); clock.UtcNow = () => lastAccessTimeUtc; fileSystem.File.ReadAllText(path); // Act IFileInfo fileInfo = fileSystem.ConstructFileInfo(path); // Assert fileInfo.Name.Should().Be("file.TXT"); fileInfo.Extension.Should().Be(".TXT"); fileInfo.FullName.Should().Be(path); fileInfo.DirectoryName.Should().Be(@"c:\SOME"); fileInfo.Exists.Should().BeTrue(); fileInfo.Length.Should().Be(DefaultContents.Length); fileInfo.IsReadOnly.Should().BeFalse(); fileInfo.Attributes.Should().Be(FileAttributes.Archive); fileInfo.CreationTime.Should().Be(creationTimeUtc.ToLocalTime()); fileInfo.CreationTimeUtc.Should().Be(creationTimeUtc); fileInfo.LastAccessTime.Should().Be(lastAccessTimeUtc.ToLocalTime()); fileInfo.LastAccessTimeUtc.Should().Be(lastAccessTimeUtc); fileInfo.LastWriteTime.Should().Be(lastWriteTimeUtc.ToLocalTime()); fileInfo.LastWriteTimeUtc.Should().Be(lastWriteTimeUtc); fileInfo.ToString().Should().Be(path); IDirectoryInfo directoryInfo = fileInfo.Directory.ShouldNotBeNull(); directoryInfo.FullName.Should().Be(@"c:\SOME"); }
public IFileInfo Zip(IDirectoryInfo directory) { if (directory == null) { throw new ArgumentNullException("directory"); } if (!(new MutatingFileSystem()).DirectoryExists(directory.FullName)) { throw new DirectoryNotFoundException(directory.FullName); } return(new RealFileInfo(Greg.Utility.FileUtilities.Zip(directory.FullName))); }
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 void When_creating_above_root_of_drive_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .Build(); // Act IDirectoryInfo info = fileSystem.Directory.CreateDirectory(@"C:\..\..\store"); // Assert info.Should().NotBeNull(); info.FullName.Should().Be(@"C:\store"); fileSystem.Directory.Exists(@"C:\store").Should().BeTrue(); }
/// <summary> /// Retreives all files in supplied directories. /// </summary> /// <param name="directory">Directory whose parent to check.</param> /// <param name="attributes">Attributes the parent must have.</param> /// <returns><code>true</code> if any of the parents have an attribute, <code>false</code> otherwise.</returns> public static bool ParentHasAttribute(this IDirectoryInfo directory, params FileAttributes[] attributes) { if (directory == null) { throw new ArgumentNullException("directory"); } if (attributes == null) { throw new ArgumentNullException("attributes"); } var parent = directory.Parent; return(ParentHasAttributeHelper(attributes, parent)); }
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); }
protected virtual IList <SyncOperation> ResolveOperations(IDirectoryInfo source, IDirectoryInfo target, List <IFileInfo> targetFiles, List <IDirectoryInfo> targetDirectories, List <IFileInfo> sourceFiles, List <IDirectoryInfo> sourceDirectories) { const string actionName = "Resolving sync operations ..."; Log.Debug(actionName); OnActionChanged(actionName); var operations = _syncResolver.ResolveSync(source, sourceDirectories, sourceFiles, target, targetDirectories, targetFiles, Filters); ProgressPercentage += SyncResolverAllocationPercentage; CheckStopped(); return(operations); }
/// <summary> /// Processes a single file. /// </summary> /// <param name="type"> /// The sort type to use. /// </param> /// <param name="file"> /// The file to process. /// </param> /// <param name="destination"> /// The destination to process the files to. /// </param> private void ProcessFile(SortType type, FileResult file, IDirectoryInfo destination) { var destinationInfo = fileResultManager.GetFullPath(file, destination); if (destinationInfo.Directory != null && !destinationInfo.Directory.Exists) { destinationInfo.Directory.Create(); } else { if (!HandleRenameAndOverwrite(file, destination, ref destinationInfo)) { return; } } if (destinationInfo.Exists) { Logger.OnLogMessage( this, "Skipping {0}. Already exists.", LogType.Info, destinationInfo.Name.Truncate()); return; } switch (type) { case SortType.Move: file.InputFile.MoveTo(destinationInfo.FullName); Logger.OnLogMessage(this, "Moved {0}", LogType.Info, file.InputFile.Name.Truncate()); if (settings.DeleteEmptySubdirectories) { DeleteEmptySubdirectories(file); } break; case SortType.Copy: file.InputFile.CopyTo(destinationInfo.FullName); Logger.OnLogMessage(this, "Copied {0}", LogType.Info, file.InputFile.Name.Truncate()); break; } foreach (var episode in file.Episodes) { episode.FileCount++; episode.Save(storageProvider); } }
protected override void GivenThat() { base.GivenThat(); _controlFile = TestControlFileFactory.CreateControlFile(); _environmentInformationProvider = GenerateMock <IEnvironmentInformationProvider>(); _directoryInfo = GenerateMock <IDirectoryInfo>(); SetupData(); SetupStubs(); _generator = new CommandGenerator(_environmentInformationProvider); }
public void DirectoriesValidationResultIsSuccess() { // Prepare int maxFileSize = 10; IConfiguration configuration = MockFactory.ConfigurationWithMaximumFileSizeOf(maxFileSize); MaximumFileSizeValidation validation = new MaximumFileSizeValidation(configuration); IDirectoryInfo directory = MockFactory.DirectoryWithName("a_directory_name"); // Exercise IValidationResult validationResult = validation.Validate(directory); // Verify AssertExtension.ValidationResultIsSuccess(validationResult, "A directory triggers a maximum file size validation error."); }
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>()); } }
private void When_creating_remote_directory_tree_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingDirectory(@"\\teamshare\folder") .Build(); // Act IDirectoryInfo info = fileSystem.Directory.CreateDirectory(@"\\teamshare\folder\documents\for\us"); // Assert info.Should().NotBeNull(); fileSystem.Directory.Exists(@"\\teamshare\folder\documents\for\us").Should().BeTrue(); }
private IDirectoryInfo GetDirectoryPath(IDirectoryInfo directoryPath, string subDirectory) { if (string.IsNullOrEmpty(subDirectory)) { return(directoryPath); } var target = directoryPath.GetDirectories(subDirectory, SearchOption.TopDirectoryOnly).FirstOrDefault(); if (target == null || !target.Exists) { target = directoryPath.CreateSubdirectory(subDirectory); } return(target); }
// ****************************************************************************** /// <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); }
private bool ShouldBrowseDirectory(IDirectoryInfo directory) { var result = true; if (!directory.Exists) { _log.DebugFormat("Skipping scanning directory {0}.", directory.FullName); result = false; } else if (directory.Parent == null) { // ReSharper disable RedundantAssignment result = true; // ReSharper restore RedundantAssignment } else if (_defautExclussions.Contains(directory.Name) && (directory.Attributes & FileAttributes.System) == FileAttributes.System) { _log.DebugFormat("Skipping scanning directory {0} because it is directory that is a part of default exclusion.", directory.FullName); result = false; } else if ((directory.Attributes & FileAttributes.Offline) == FileAttributes.Offline || (directory.Attributes & FileAttributes.Device) == FileAttributes.Device) { _log.DebugFormat("Skipping scanning directory {0} because it is a Offline or a Device.", directory.FullName); result = false; } else if (!ScanSystem && (directory.Attributes & FileAttributes.System) == FileAttributes.System) { _log.DebugFormat("Skipping scanning directory {0} because it is a System directory.", directory.FullName); result = false; } else if (!ScanHidden && (directory.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { _log.DebugFormat("Skipping scanning directory {0} because it is a Hidden directory.", directory.FullName); result = false; } if (IncludeFilters.Count > 0 && !FindFilesRegEx.MatchesFilePattern(directory.FullName, IncludeFilters.ToArray())) { return(false); } if (ExcludeFilters.Count > 0 && FindFilesRegEx.MatchesFilePattern(directory.FullName, ExcludeFilters.ToArray())) { return(false); } return(result); }
/// <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(); } }
public void WhenLocalDirectoryPathIsTooLongValidationResultIsError() { // Prepare int maxPathLength = 20; IConfiguration configuration = MockFactory.ConfigurationWithMaximumPathLengthOf(maxPathLength); MaximumPathLengthValidation validation = new MaximumPathLengthValidation(configuration); string tooLongPath = "C:/asdfasdf/asdfasdf/asdfasdf"; IDirectoryInfo directory = MockFactory.DirectoryWithPath(tooLongPath); // Exercise IValidationResult validationResult = validation.Validate(directory); // Verify AssertExtension.ValidationResultIsError(validationResult, "Directory with too long path does not trigger an error."); }
public static async Task <IFileInfo> CopyFileAsync(this IDirectoryInfo directory, IFileInfo file, string fileName, CancellationToken ct) { if (directory == null) { throw new ArgumentNullException(nameof(directory)); } if (file == null) { throw new ArgumentNullException(nameof(file)); } using var inputStream = await file.OpenReadAsync(ct).ConfigureAwait(false); return(await directory.CreateFileAsync(fileName, inputStream, file.Length, ct).ConfigureAwait(false)); }
private void When_getting_directory_parent_for_parent_parent_directory_that_exists_as_file_it_must_succeed() { // Arrange IFileSystem fileSystem = new FakeFileSystemBuilder() .IncludingEmptyFile(@"C:\some\file.txt") .Build(); // Act IDirectoryInfo parent = fileSystem.Directory.GetParent(@"C:\some\file.txt\deeper\more"); // Assert IDirectoryInfo parentNotNull = parent.ShouldNotBeNull(); parentNotNull.FullName.Should().Be(@"C:\some\file.txt\deeper"); }
public void WhenLocalDirectoryTreeDepthIsEqualToMaxDepthValidationResultIsSuccess() { // Prepare int maxDepth = 4; IConfiguration configuration = MockFactory.ConfigurationWithMaximumDepthOf(maxDepth); MaximumTreeDepthValidation validation = new MaximumTreeDepthValidation(configuration); var path = Path.Combine(@"C:\", "first", "second", "third", "fourth"); IDirectoryInfo directory = MockFactory.DirectoryWithPath(path); // Exercise IValidationResult validationResult = validation.Validate(directory); // Verify AssertExtension.ValidationResultIsSuccess(validationResult, "Local file with depth equal to max depth triggers an error."); }
public void WhenDirectoryNameLengthIsEqualToMaxLengthValidationResultIsSuccess() { // Prepare int maxFilenameLength = 3; IConfiguration configuration = MockFactory.ConfigurationWithMaximumFilenameLength(maxFilenameLength); MaximumFilenameLengthValidation validation = new MaximumFilenameLengthValidation(configuration); string dirName = "abc"; IDirectoryInfo directory = MockFactory.DirectoryWithName(dirName); // Exercise IValidationResult validationResult = validation.Validate(directory); // Verify AssertExtension.ValidationResultIsSuccess(validationResult, "File with name of length equal to max length triggers an error."); }
public IFileInfo ZipFile(IDirectoryInfo destDirectory) { IFileInfo zipFile = _fileSystem.FileInfo.FromFileName(Path.Combine(destDirectory.FullName, Path.ChangeExtension(_sourceFile.Name, ".zip"))); if (zipFile.Exists) { string warnMessage = $"File: {zipFile.Name} already exists in Import-Directory"; Log.Logger.Warn(warnMessage); } else { Create(zipFile); } return(zipFile); }
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 WhenDirectoryNameIsTooLongValidationResultIsError() { // Prepare int maxFilenameLength = 3; IConfiguration configuration = MockFactory.ConfigurationWithMaximumFilenameLength(maxFilenameLength); MaximumFilenameLengthValidation validation = new MaximumFilenameLengthValidation(configuration); string tooLongName = "abcd"; IDirectoryInfo directory = MockFactory.DirectoryWithName(tooLongName); // Exercise IValidationResult validationResult = validation.Validate(directory); // Verify AssertExtension.ValidationResultIsError(validationResult, "File with too long name does not trigger an error."); }
public void Setup() { _fileInfoFactory = new SystemFileInfoFactory(); _directoryInfo = new SystemIoDirectoryInfo(); var di = new DirectoryInfo(BaseDirectory); if (di.Exists) { di.Delete(true); } di.Create(); _houseHoldingFileRepository = new HouseHoldingFileRepository(BaseDirectory, _fileInfoFactory, _directoryInfo); CreateFiles(BaseDirectory); }
private async Task <IEnumerable <IFileInfo> > ListFilesRecursiveAsync(IDirectoryInfo folder) { IEnumerable <IFileInfo> files = await folder.EnumerateFilesAsync(); var subfolders = await folder.EnumerateDirectoriesAsync(); foreach (var i in subfolders) { var subfolderFiles = await ListFilesRecursiveAsync(i); files = files.Concat(subfolderFiles); } return(files); }