Search code examples
c#access-deniedunauthorizedaccessexcepti

unauthorized access exception c#


I have this method

 public void Copy(string sourcePath, string destPath)
 {
     string[] files= Directory.GetFiles(sourcePath);
     for (int i = 0; i < files.Length; i++)
     {
         try
         {
             File.Copy(files[i], destPath);
         }
         catch
         {
             try
             {
                 File.Replace(files[i], destPath, null);
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
         }
    }
}

when I run it I get unauthorized access exception , Access denied ! any help in this !


Solution

  • This exception is covered in the documentation for File.Copy:

    The caller does not have the required permission.
    -or-
    destFileName is read-only.
    

    Check the attributes of the file after the first copy. Are the permissions what you expect? Do you need your program to run elevated (as administrator)?