Ateeq
Ateeq

Reputation: 823

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 !

Upvotes: -1

Views: 5446

Answers (3)

h-ascii_huskie
h-ascii_huskie

Reputation: 1

When the problem occurs on a Windows machine, make sure you have disabled "controlled folder access" in the App Windows-Safety or allow folder access to your program. (must have administrator privileges)

Upvotes: 0

Kumar Manish
Kumar Manish

Reputation: 3772

below reasons can possible :

The sourceFileName or destinationFileName parameter specifies a file that is read-only.

-or- This operation is not supported on the current platform.

-or- Source or destination parameters specify a directory instead of a file.

-or- The caller does not have the required permission.

Read link :http://msdn.microsoft.com/en-us/library/9etk7xw2(v=vs.110).aspx

Upvotes: 1

Dhaval Patel
Dhaval Patel

Reputation: 7601

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)?

Upvotes: 3

Related Questions