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

本秂侑毒 提交于 2019-11-29 15:09:32

问题


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:\


回答1:


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>();
                }
            }));
    }



回答2:


File system objects are subject to security. Some file system objects are secured in such a way that they can only be accessed by certain users. You are encountering a file to which the user executing the code does not have sufficient rights to access.

The reason that you don't have access rights for this particular folder is to protect the security of the different users on the system. 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.

Perhaps the simplest way around this is to skip hidden folders at the root level of the drive. That simple change would be enough to solve your problem because you surely don't want to copy recycle bins.




回答3:


That folder is a secure system folder (your bin, each drive has its own bin). Just place your file.copy into a try catch statement and ignore/log all the failures. That way you will only copy actual files and skip system files/folders.

If you really want to avoid the try catch statement. Use the fileinfo and directory info classes to figure out which folders/files are of the system and will throw an exception.



来源:https://stackoverflow.com/questions/22474882/access-to-the-path-c-recycle-bin-s-1-5-18-is-denied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!