Question : How to Take ownership of folder and all subdirectories and files?

I am trying to take ownership of a user's profile using .net 2.0.  I can do this manually since I am in the admin group.  Here is the code that fails:

            Dim dinfo As New DirectoryInfo(profile)
            Dim dir As DirectorySecurity = dinfo.GetAccessControl
            Dim account As NTAccount = New NTAccount(WindowsIdentity.GetCurrent.Name)
 
            dir.SetOwner(account)

Code fails at dinfo.GetAccessControl.  I get this message:  UnauthorizedAccessException was unhandled by user code.

I'm I doing something wrong.  Is there another method?


Answer : How to Take ownership of folder and all subdirectories and files?

Let's try one more thing before we "bring out the big guns"...  

        Dim ds As System.Security.AccessControl.DirectorySecurity
        Dim account As System.Security.Principal.NTAccount

        ' use the static GetAccessControl method
        ds = System.IO.Directory.GetAccessControl(profile, Security.AccessControl.AccessControlSections.Owner)

        ' set the owner
        account = New System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent.Name)
        ds.SetOwner(account)

        ' save the changes using the static SetAccessControl method
        System.IO.Directory.SetAccessControl(profile, ds)

If that fails, we can always switch over to using the APIs.  Here is an article with downloadable sample VB.Net code that does precisely that:   http://home.hot.rr.com/graye/Articles/ChangeOwner.htm
Random Solutions  
 
programming4us programming4us