Access to the path 'c:\$Recycle.Bin\S-1-5-18' is denied

前端 未结 4 830
天涯浪人
天涯浪人 2020-12-31 22:05

I have this code to copy all files from source-directory, F:\\, to destination-directory.

public void Copy(string sourceDir, string targetDir)
{         


        
4条回答
  •  轮回少年
    2020-12-31 22:50

    This should do the trick:

    private IEnumerable RecursiveFileSearch(string path, string pattern, ICollection filePathCollector = null)
    {
        try
        {
            filePathCollector = filePathCollector ?? new LinkedList();
    
            var matchingFilePaths = Directory.GetFiles(path, pattern);
    
            foreach(var matchingFile in matchingFilePaths)
            {
                filePathCollector.Add(matchingFile);
            }
    
            var subDirectories = Directory.EnumerateDirectories(path);
    
            foreach (var subDirectory in subDirectories)
            {
                RecursiveFileSearch(subDirectory, pattern, filePathCollector);
            }
    
            return filePathCollector;
        }
        catch (Exception error)
        {
            bool isIgnorableError = error is PathTooLongException ||
                error is UnauthorizedAccessException;
    
            if (isIgnorableError)
            {
                return Enumerable.Empty();
            }
    
            throw error;
        }
    }
    

提交回复
热议问题