EnumerateDirectories() public static method

public static EnumerateDirectories ( string path ) : System.Collections.Generic.IEnumerable
path string
return System.Collections.Generic.IEnumerable
示例#1
0
        public IEnumerable <string> GetRoots()
        {
            ConcurrentQueue <string> inputs = new ConcurrentQueue <string>();
            var items = _configuration.GetValues(PATHS_SETTING)
                        .Where(p => !(string.IsNullOrWhiteSpace(p)));

            foreach (var item in items)
            {
                yield return(item);

                inputs.Enqueue(item);
            }

            string current = null;

            while (inputs.TryDequeue(out current))
            {
                var childItems = Directory.EnumerateDirectories(current);
                foreach (var item in childItems)
                {
                    yield return(item);

                    inputs.Enqueue(item);
                }
            }
        }
示例#2
0
        private void CopyDirectory(string sourceFolder, string destinationFolder)
        {
            // check that source and destination folders exist
            if (!sourceFolder.DirectoryExists() || !destinationFolder.DirectoryExists())
            {
                return;
            }

            // copy the files over
            foreach (var file in Directory.EnumerateFiles(sourceFolder))
            {
                File.Copy(file, Path.Combine(destinationFolder, Path.GetFileName(file)), true);
            }

            // copy the directories over
            foreach (var directory in Directory.EnumerateDirectories(sourceFolder))
            {
                var destinationDirName = Path.Combine(destinationFolder, Path.GetFileName(directory));

                if (!Directory.Exists(destinationDirName))
                {
                    Directory.CreateDirectory(destinationDirName);
                }

                CopyDirectory(directory, destinationDirName);
            }
        }
        public void Search_FilteredFileFindedExcludeFileSystemEntry_RiseStartAndFinishEventsFindOnlyDirectories()
        {
            // Arrange
            var fsv = new FileSystemVisitor();

            var isStartEventRised  = false;
            var isFinishEventRised = false;

            fsv.Start              += (sender, args) => { isStartEventRised = true; };
            fsv.Finish             += (sender, args) => { isFinishEventRised = true; };
            fsv.FilteredFileFinded += (sender, args) => { args.ExcludeFileSystemEntry = true; };

            // Act
            var findedEntries = fsv.Search(TestRootDirectoryName).ToArray();

            // Assert
            Assert.IsTrue(isStartEventRised);
            Assert.IsTrue(isFinishEventRised);

            var expectedEntries = DirectoryHelper.EnumerateDirectories(TestRootDirectoryName, "*", SearchOption.AllDirectories).ToArray();

            Assert.IsTrue(ArrayHelper.Compare(
                              expectedEntries,
                              findedEntries,
                              StringComparison)
                          );
        }
示例#4
0
        public static IEnumerable <Backup> EnumerateBackups(bool isMac)
        {
            string backupRootPath;

            if (isMac)
            {
                backupRootPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                    "Library",
                    "ApplicationSupport",
                    "MobileSync",
                    "Backup"
                    );
            }
            else
            {
                backupRootPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "Apple Computer",
                    "MobileSync",
                    "Backup"
                    );
            }

            if (!IODirectory.Exists(backupRootPath))
            {
                yield break;
            }

            foreach (var backupDirectory in IODirectory.EnumerateDirectories(backupRootPath))
            {
                // Check if this is a backup we can deal with. It has to have an Info.plist and a Manifest.db.
                var plistFile = Path.Combine(backupDirectory, "Info.plist");
                var manifest  = Path.Combine(backupDirectory, "Manifest.db");

                if (!IOFile.Exists(plistFile) || !IOFile.Exists(manifest))
                {
                    continue;
                }

                var plist  = PDictionary.FromFile(plistFile);
                var backup = new Backup {
                    BackupPath   = backupDirectory,
                    DeviceName   = plist.GetString("Device Name"),
                    OSVersion    = Version.Parse(plist.GetString("Product Version")),
                    ProductName  = plist.GetString("Product Name"),
                    ProductType  = plist.GetString("Product Type"),
                    SerialNumber = plist.GetString("Serial Number"),
                    BackupTime   = plist.Get <PDate>("Last Backup Date").Value,
                };

                yield return(backup);
            }
        }
        private void RecursiveDeleteEmptyDirectories(string dir, bool importfolder)
        {
            try
            {
                if (string.IsNullOrEmpty(dir))
                {
                    return;
                }
                if (!Directory.Exists(dir))
                {
                    return;
                }
                if (IsDirectoryEmpty(dir))
                {
                    if (importfolder)
                    {
                        return;
                    }
                    try
                    {
                        Directory.Delete(dir);
                    }
                    catch (Exception ex)
                    {
                        if (ex is DirectoryNotFoundException || ex is FileNotFoundException)
                        {
                            return;
                        }
                        logger.Warn("Unable to DELETE directory: {0} Error: {1}", dir,
                                    ex);
                    }
                    return;
                }

                // If it has folder, recurse
                foreach (string d in Directory.EnumerateDirectories(dir))
                {
                    RecursiveDeleteEmptyDirectories(d, false);
                }
            }
            catch (Exception e)
            {
                if (e is FileNotFoundException || e is DirectoryNotFoundException)
                {
                    return;
                }
                logger.Error($"There was an error removing the empty directory: {dir}\r\n{e}");
            }
        }
示例#6
0
    private static IEnumerable <string> EnumerateDirectoriesInternal(
        string path,
        string searchPattern,
        bool recursively)
    {
        var localPath = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        var localSearchPattern = Requires.NotNullOrWhiteSpace(
            searchPattern,
            nameof(searchPattern));

        return(FSDir.EnumerateDirectories(
                   localPath,
                   localSearchPattern,
                   recursively ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
    }
示例#7
0
        private void RemoveDirectory(string directoryFolder)
        {
            // remove all files
            foreach (var fileToBeRemoved in Directory.EnumerateFiles(directoryFolder))
            {
                fileToBeRemoved.TryHardToDelete();
            }

            // remove all subdirectories
            foreach (var folderToBeRemoved in Directory.EnumerateDirectories(directoryFolder))
            {
                RemoveDirectory(folderToBeRemoved);
            }

            try
            {
                // now try to remove the directory
                Directory.Delete(directoryFolder);
            }
            catch { }
        }
        public void Search_DirectoryFindedWithFalseFilter_RiseEventForEachSubdirectoryInDirectory()
        {
            // Arrange
            var fsv = new FileSystemVisitor((path) => false);

            var findedDirectories = new List <string>();

            fsv.DirectoryFinded += (sender, args) => { findedDirectories.Add(args.Path); };

            // Act
            fsv.Search(TestRootDirectoryName).ToArray();

            // Assert
            var expectedEntries = DirectoryHelper.EnumerateDirectories(TestRootDirectoryName, "*", SearchOption.AllDirectories).ToArray();

            Assert.IsTrue(ArrayHelper.Compare(
                              expectedEntries,
                              findedDirectories.ToArray(),
                              StringComparison)
                          );
        }
示例#9
0
    private static Task <IEnumerable <string> > EnumerateDirectoriesInternalAsync(
        string path,
        string searchPattern,
        bool recursively,
        CancellationToken cancellationToken)
    {
        var localPath = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        var localSearchPattern = Requires.NotNullOrWhiteSpace(
            searchPattern,
            nameof(searchPattern));

        return(Work.OnThreadPoolAsync(
                   state => FSDir.EnumerateDirectories(
                       state.Path,
                       state.Pattern,
                       state.Recursive),
                   (Path: localPath, Pattern: localSearchPattern, Recursive: recursively ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly),
                   cancellationToken));
    }
示例#10
0
        /// <summary>
        /// Extract zipped package and return the unzipped folder
        /// </summary>
        /// <param name="zippedPackagePath"></param>
        /// <returns></returns>
        private string ExtractZipPackage(string zippedPackagePath)
        {
            if (zippedPackagePath != null && zippedPackagePath.FileExists())
            {
                // extracted folder
                string extractedFolder = FilesystemExtensions.GenerateTemporaryFileOrDirectoryNameInTempDirectory();

                try
                {
                    //unzip the file
                    ZipFile.ExtractToDirectory(zippedPackagePath, extractedFolder);

                    // extraction fails
                    if (!Directory.Exists(extractedFolder))
                    {
                        Verbose(string.Format(CultureInfo.CurrentCulture, Resources.Messages.FailToExtract, zippedPackagePath, extractedFolder));
                        return(string.Empty);
                    }

                    // the zipped folder
                    var zippedDirectory = Directory.EnumerateDirectories(extractedFolder).FirstOrDefault();

                    if (!string.IsNullOrWhiteSpace(zippedDirectory) && Directory.Exists(zippedDirectory))
                    {
                        return(zippedDirectory);
                    }
                }
                catch (Exception ex)
                {
                    Verbose(string.Format(CultureInfo.CurrentCulture, Resources.Messages.FailToInstallZipFolder, zippedPackagePath, ex.Message));
                    Debug(ex.StackTrace);

                    // remove the extracted folder
                    extractedFolder.TryHardToDelete();
                }
            }

            return(string.Empty);
        }
示例#11
0
        public bool DeleteEntries()
        {
            void DeleteCore(string path)
            {
                foreach (var file in D.EnumerateFiles(path))
                {
                    File.Delete(file);
                }

                foreach (var dir in D.EnumerateDirectories(path))
                {
                    DeleteCore(dir);
                    D.Delete(dir);
                }
            }

            if (!this.Exists())
            {
                return(false);
            }
            DeleteCore(this.FullName);
            return(true);
        }
示例#12
0
文件: FileSystem.cs 项目: pk8est/Antd
 public static void CopyDirectory(string source, string destination)
 {
     IoDir.CreateDirectory(source);
     IoDir.CreateDirectory(destination);
     foreach (var dirPath in IoDir.EnumerateDirectories(source, "*", SearchOption.AllDirectories))
     {
         try {
             IoDir.CreateDirectory(dirPath.Replace(source, destination));
         }
         catch (Exception) {
             Bash.Execute($"mkdir -p {dirPath.Replace(source, destination)}", false);
         }
     }
     foreach (var newPath in IoDir.EnumerateFiles(source, "*", SearchOption.AllDirectories))
     {
         try {
             File.Copy(newPath, newPath.Replace(source, destination), true);
         }
         catch (Exception) {
             Bash.Execute($"cp {newPath} {newPath.Replace(source, destination)}", false);
         }
     }
 }
示例#13
0
        /// <summary>
        /// Copies a directory to a new location including all files and folders beneath it.
        /// Creates a new directory if necessary.
        /// </summary>
        /// <param name="path">The path of the directory to copy.</param>
        /// <param name="newPath">The destination path to copy the directory to.</param>
        /// <param name="overwrite">Whether to overwrite any existing files in the directory being copied to.</param>
        /// <returns>True if the directory was copied. False otherwise.</returns>
        static public bool Copy(string path, string newPath, bool overwrite = false)
        {
            if (!string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(newPath))
            {
                // Ensure that the paths end in a slash.
                if (!path.EndsWith(@"\"))
                {
                    // Add the slash.
                    path += @"\";
                }

                if (!newPath.EndsWith(@"\"))
                {
                    // Add the slash.
                    newPath += @"\";
                }

                // Determine if the path is a directory.
                if (SystemDirectory.Exists(path))
                {
                    // It is a directory.
                    try
                    {
                        // Check whether the directory to copy to exists.
                        if (!SystemDirectory.Exists(newPath))
                        {
                            // Clone a new directory to copy the directory into.
                            // This ensures we get the same permissions.
                            if (!Clone(path, newPath))
                            {
                                // The directory couldn't be cloned.
                                return(false);
                            }
                        }

                        // Copy the contents of subdirectories.
                        foreach (string directoryName in SystemDirectory.EnumerateDirectories(path))
                        {
                            // Get the name of the subdirectory.
                            string subDirectoryName = directoryName.Substring(path.Length);

                            // Recursively copy the directory.
                            if (!Copy(directoryName, newPath + subDirectoryName + @"\", overwrite))
                            {
                                // The directory couldn't be copied.
                                return(false);
                            }
                        }

                        // Copy any files in the directory.
                        foreach (string fileName in SystemDirectory.EnumerateFiles(path))
                        {
                            FileInfo originalFileInfo = new FileInfo(fileName);
                            if (!File.Copy(fileName, newPath, overwrite))
                            {
                                // The file couldn't be copied.
                                return(false);
                            }
                        }

                        return(true);
                    }
                    catch
                    {
                        // There was an error copying the directory or its contents.
                        return(false);
                    }
                }
            }
            // The path or newPath were null, or the path to clone did not exist.
            return(false);
        }
示例#14
0
 public IEnumerable <FileSystemPath> EnumerateAllEntries(string searchPattern = "*")
 => D.EnumerateDirectories(this.FullName, searchPattern, SearchOption.AllDirectories).Select(x => (FileSystemPath) new DirectoryPath(x, false))
 .Concat(D.EnumerateFiles(this.FullName, searchPattern, SearchOption.AllDirectories).Select(x => (FileSystemPath) new FilePath(x, false)));
示例#15
0
 public IEnumerable <DirectoryPath> EnumerateAllDirectories(string searchPattern = "*")
 => D.EnumerateDirectories(this.FullName, searchPattern, SearchOption.AllDirectories).Select(x => new DirectoryPath(x, false));
示例#16
0
        private IEnumerable <DriveItem> SafelyEnumerateDriveItems(string folderPath, CryptoDriveContext context, [CallerMemberName] string callerName = "")
        {
            var forceNew           = callerName == nameof(this.SafelyEnumerateDriveItems);
            var driveItems         = Enumerable.Empty <DriveItem>();
            var absoluteFolderPath = folderPath.ToAbsolutePath(this.BasePath);

            try
            {
                // get all folders in current folder
                driveItems = driveItems.Concat(Directory.EnumerateDirectories(absoluteFolderPath, "*", SearchOption.TopDirectoryOnly)
                                               .SelectMany(current =>
                {
                    RemoteState oldRemoteState = null;
                    var driveInfo   = new DirectoryInfo(current).ToDriveItem(this.BasePath);
                    var folderPath2 = current.Substring(this.BasePath.Length).NormalizeSlashes();

                    if (!forceNew)
                    {
                        oldRemoteState = context.RemoteStates.FirstOrDefault(remoteState => remoteState.GetItemPath() == folderPath2 &&
                                                                             remoteState.Type == DriveItemType.Folder);
                    }

                    // When we know that the parent folder is not in the database (oldRemoteState == null),
                    // the children aren't there neither (forceNew = true).
                    if (forceNew || oldRemoteState == null)
                    {
                        return(this.SafelyEnumerateDriveItems(folderPath2, context)
                               .Concat(new DriveItem[] { driveInfo }));
                    }
                    else
                    {
                        return new List <DriveItem> {
                            driveInfo
                        }
                    };
                }));

                // get all files in current folder
                driveItems = driveItems.Concat(Directory.EnumerateFiles(absoluteFolderPath)
                                               .SelectMany(current =>
                {
                    var driveInfo = new FileInfo(current).ToDriveItem(this.BasePath);
                    return(new List <DriveItem> {
                        driveInfo
                    });
                }).ToList());

                // get all deleted items
                var remoteStates = context.RemoteStates.Where(current => current.Path == folderPath);

                var deletedItems = remoteStates.Where(current =>
                {
                    switch (current.Type)
                    {
                    case DriveItemType.Folder:
                        return(!Directory.Exists(current.GetItemPath().ToAbsolutePath(this.BasePath)));

                    case DriveItemType.File:
                        return(!File.Exists(current.GetItemPath().ToAbsolutePath(this.BasePath)));

                    case DriveItemType.RemoteItem:
                    default:
                        throw new NotSupportedException();
                    }
                }).Select(current => current.ToDriveItem(deleted: true));

                driveItems = driveItems.Concat(deletedItems);

                return(driveItems);
            }
            catch (UnauthorizedAccessException)
            {
                return(driveItems);
            }
        }