none
C# unauthorizedAccessException when trying to programmically copying folder

    Question

  • Hello.

    Im making an application which should be able to make a backup of a selected folder from a treeview and place it in a specified folder. When I try to copy the folder I get an exception;

    System.UnauthorizedAccessException was unhandled
      Message="Access to the path 'C:\\ProjektTest\\D000002' is denied."
      Source="mscorlib"
      StackTrace:
           at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
           at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite)
           at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
           at Welding_Program.History.treeView1_KeyPress(Object sender, KeyPressEventArgs e) in C:\Documents and Settings\xx\xx\xx\xx\xx\xx\xx\History.cs:line 208
           at System.Windows.Forms.Control.OnKeyPress(KeyPressEventArgs e)
           at System.Windows.Forms.TreeView.OnKeyPress(KeyPressEventArgs e)
           at System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m)
           at System.Windows.Forms.Control.ProcessKeyMessage(Message& m)
           at System.Windows.Forms.Control.WmKeyChar(Message& m)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.TreeView.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at Welding_Program.Program.Main() in C:\Documents and Settings\xx\xx\xx\xx\xx\xx\xx\Program.cs:line 18
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException:

    Is there some way I can give my application permission to to copy the folder?
    My machine is running Windows XP.

    Thank you for your time.
    Thursday, November 05, 2009 1:34 PM

Answers

  • ...you can make use of "DirectorySecurity Class". This class represents the access control and audit security for a directory.

    refer: http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.directorysecurity.aspx

            // Adds an ACL entry on the specified directory for the specified account.
            public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
            {
                // Create a new DirectoryInfo object.
                DirectoryInfo dInfo = new DirectoryInfo(FileName);
    
                // Get a DirectorySecurity object that represents the 
                // current security settings.
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
    
                // Add the FileSystemAccessRule to the security settings. 
                dSecurity.AddAccessRule(new FileSystemAccessRule(Account, Rights, ControlType));
    
                // Set the new access settings.
                dInfo.SetAccessControl(dSecurity);
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                string DirectoryName = "sampleDIR";
                // Add the access control entry to the directory.
                AddDirectorySecurity(DirectoryName, @"MYDOMAIN\BALAJIBASKAR", FileSystemRights.ReadData, AccessControlType.Allow); 
            }
    

    Balaji Baskar [Please mark the post as answer if it answers your question]
    • Marked as answer by Roahn Luo Monday, November 09, 2009 9:19 AM
    Thursday, November 05, 2009 4:09 PM
  • Thank you very much for your help!

    I got it working now. Heres the code that sets the permission in my app:

    ---------
    public static void SetAccessRule(string directory)
            {
                System.Security.AccessControl.DirectorySecurity sec = System.IO.Directory.GetAccessControl(directory);
                FileSystemAccessRule accRule = new FileSystemAccessRule(Environment.UserDomainName + "\\" + Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow);
                sec.AddAccessRule(accRule);
            }
    ---------


    • Marked as answer by Roahn Luo Monday, November 09, 2009 9:19 AM
    Friday, November 06, 2009 12:30 PM

All replies

  • Are you running the application out of the Intranet zone?  It needs to be run locally to have access to local resources.  You'd need to share that location if you want it available to the Intranet zone.
    Thursday, November 05, 2009 1:38 PM
  • Im sorry - Im not even sure what the Intranet zone is? I am running the app on the computer I am making the app on. And the path I want to copy from and to is on my computer. Dunno if it isthis you are reffering to?
    Thursday, November 05, 2009 1:45 PM
  • Intranet zone is an element of web browsing.  It is irrelevant here.  Sounds like you need to give yourself read permissions to all the directories you wish to copy.  Personally, I would use Xcopy and wrap this up as a process, but you need to fix the permission issue first.
    Good coding involves knowing one's logical limits and expanding them as necessary.
    Thursday, November 05, 2009 3:22 PM
  • ...you can make use of "DirectorySecurity Class". This class represents the access control and audit security for a directory.

    refer: http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.directorysecurity.aspx

            // Adds an ACL entry on the specified directory for the specified account.
            public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
            {
                // Create a new DirectoryInfo object.
                DirectoryInfo dInfo = new DirectoryInfo(FileName);
    
                // Get a DirectorySecurity object that represents the 
                // current security settings.
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
    
                // Add the FileSystemAccessRule to the security settings. 
                dSecurity.AddAccessRule(new FileSystemAccessRule(Account, Rights, ControlType));
    
                // Set the new access settings.
                dInfo.SetAccessControl(dSecurity);
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                string DirectoryName = "sampleDIR";
                // Add the access control entry to the directory.
                AddDirectorySecurity(DirectoryName, @"MYDOMAIN\BALAJIBASKAR", FileSystemRights.ReadData, AccessControlType.Allow); 
            }
    

    Balaji Baskar [Please mark the post as answer if it answers your question]
    • Marked as answer by Roahn Luo Monday, November 09, 2009 9:19 AM
    Thursday, November 05, 2009 4:09 PM
  • Thank you very much for your help!

    I got it working now. Heres the code that sets the permission in my app:

    ---------
    public static void SetAccessRule(string directory)
            {
                System.Security.AccessControl.DirectorySecurity sec = System.IO.Directory.GetAccessControl(directory);
                FileSystemAccessRule accRule = new FileSystemAccessRule(Environment.UserDomainName + "\\" + Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow);
                sec.AddAccessRule(accRule);
            }
    ---------


    • Marked as answer by Roahn Luo Monday, November 09, 2009 9:19 AM
    Friday, November 06, 2009 12:30 PM