Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

public void Copy(string sourceDir, string targetDir)
{
  //Exception occurs at this line.
    string[] files = System.IO.Directory.GetFiles(sourceDir, "*.jpg", 
                                             SearchOption.AllDirectories);

    foreach (string srcPath in files)
    {
       File.Copy(srcPath, srcPath.Replace(sourceDir, targetDir), true);
    }
}

and getting an exception.

If I omit SearchOption.AllDirectories and it works but only copies files from F:\

like image 301
Umair Ayub Avatar asked Mar 18 '14 09:03

Umair Ayub


People also ask

How to empty the contents of the Recycle Bin in Windows?

Try these steps to empty the contents of the recycle bin by deleting the files and the recycle bin folder: a. Click Start,and then type cmd in the Start Search box. b. Right-click cmd in the Programs list, and then click Run as administrator.

Why can't I read other users'recycle bin files?

The folder in question is the recycle bin on that drive. And each different user has their own private recycle bin, that only they have permission to access. If anybody could access any other user's recycle bin, then users would be able to read each other's files, a clear violation of the system's security policy.

How do I open the Recycle Bin from elevated command prompt?

This opens elevated command prompt. c. In the elevated command prompt, type “rd /s /q C:\$Recycle.bin” without the quotes and press Enter. NOTE: For the other hard drive letters, substitute C: for the other hard drive letter instead.

How to use directory getaccesscontrol () on child directories?

There is more difficult way to use Directory.GetAccessControl () per child directory check to see if you have an access to a Directory before hand (this option is rather hard though - I don't really recommend this unless you know exactly how the access system works). Then, you only need to search/add the files among all accessible directories.


1 Answers

Use following function instead of System.IO.Directory.GetFiles:

IEnumerable<String> GetAllFiles(string path, string searchPattern)
    {
        return System.IO.Directory.EnumerateFiles(path, searchPattern).Union(
            System.IO.Directory.EnumerateDirectories(path).SelectMany(d =>
            {
                try
                {
                    return GetAllFiles(d,searchPattern);
                }
                catch (UnauthorizedAccessException e)
                {
                    return Enumerable.Empty<String>();
                }
            }));
    }
like image 144
Bohdan Avatar answered Oct 26 '22 15:10

Bohdan