1

I have this method to copy all images from my USB to a hard-drive, say C:\, But it throws exception for not able to access system-files/directories.

It works fine if I skip SearchOption.AllDirectories parameter, but my main purpose is to copy all images from USB and its sub-directories

 public void Copy(string sourceDir, string targetDir)
 {
     try
     {
         var files = System.IO.Directory.GetFiles(sourceDir, "*.jpg",  
                                                  SearchOption.AllDirectories);
         foreach (string srcPath in files)
         {
             File.Copy(srcPath, srcPath.Replace(sourceDir, targetDir), true);
         }
     }
     catch (System.UnauthorizedAccessException)
     {
     }
 }

How can I skip system-files/directories?

w.b
  • 11,026
  • 5
  • 30
  • 49
Umair Ayub
  • 19,358
  • 14
  • 72
  • 146
  • 1
    possible duplicate of [UnauthorizedAccessException cannot resolve Directory.GetFiles failure](http://stackoverflow.com/questions/1393178/unauthorizedaccessexception-cannot-resolve-directory-getfiles-failure) – Dmitry Mar 20 '14 at 10:03

1 Answers1

1

Something like this might help: (not tested)

foreach (string srcPath in files)
{
    FileAttributes attributes = File.GetAttributes(srcPath);
    bool isSystem = ((attributes & FileAttributes.System) == FileAttributes.System);
    bool isDirectory = ((attributes & FileAttributes.Directory) == FileAttributes.Directory); 
    if (!isSystem && !isDirectory)
    {
        File.Copy(srcPath, srcPath.Replace(sourceDir, targetDir), true);
    }
}
safetyOtter
  • 1,430
  • 14
  • 26
  • It will not work, because the exception is thrown on the `Directory.GetFiles`, not on the `File.Copy`. Here is the working [answer](http://stackoverflow.com/questions/1393178/unauthorizedaccessexception-cannot-resolve-directory-getfiles-failure) – Dmitry Mar 20 '14 at 10:38
  • ah. kinda lame that were stuck using trys for something simple like this. Thanks for the info! – safetyOtter Mar 20 '14 at 10:44