Remove Directories W10

Joined
Jun 6, 2016
Messages
53
Reaction score
2
I'm Using VS 2013 and .NET 4.51

I needed to automate remove empty directories in backup folder

I created a program in attachment, and I deletes many folders but on few it generates permit ion exception


I tried delete those directories using Windows Explore and it delete id fine,

Similar program using Java works fine

I ran all 3 scenarios from command line under my user account

1) .NET files with exception permit ion

2) Completed without any exception

3) Windows Explorer delete all folder
 

Attachments

  • Program.zip
    1.1 KB · Views: 329

Regedit32

Moderator
Joined
Mar 4, 2016
Messages
3,617
Reaction score
1,139
Could you modify your code to check User has Administrative Privileges?

Example

using System.Security.Principal;

public bool IsUserAdministrator() {
bool isAdmin;

try {
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);​
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;​
}
catch (Exception ex)
{
isAdmin = false;​
}
return isAdmin;​
}
 
Joined
Jun 6, 2016
Messages
53
Reaction score
2
Could you modify your code to check User has Administrative Privileges?

Example

using System.Security.Principal;

public bool IsUserAdministrator() {
bool isAdmin;

try {
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);​
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;​
}
catch (Exception ex)
{
isAdmin = false;​
}
return isAdmin;​
}

Thank you I checked
I have Admin righrs

Like I told before Java and Win Exporter do not have problems
 
Joined
Jun 6, 2016
Messages
53
Reaction score
2
Yes I have Admin Rights

Yes Java runs without problems

May be some problem in Registry
 

Regedit32

Moderator
Joined
Mar 4, 2016
Messages
3,617
Reaction score
1,139
Yes but I thought you were saying your program is unable to remove certain files owing to a permissions issue.

Could you clarify which files that is, and the precise error message you receive?


I know you personally have Administrator privileges, but the application [ that is, your Program ] needs to been seen by the System to be running with privileges; hence the suggestion before about coding that part into your program.
 
Joined
Jun 6, 2016
Messages
53
Reaction score
2
Thnak you I checked again using Setting if my account and I'm confused now

I Control panel I'm admin in application not


[Moderator]: I've removed one of the files you uploaded as it contained your name and email address. It's not a good idea to publicly show these details as someone might attempt to spam you or send something more malicious.
 

Attachments

  • C#Rights.png
    C#Rights.png
    176 KB · Views: 691
Last edited by a moderator:

Regedit32

Moderator
Joined
Mar 4, 2016
Messages
3,617
Reaction score
1,139
I can see you are the Administrator on your computer.

What this means is your User Account belongs to the Administrative Group and has privileges to modify folders or files, and perform other tasks on your computer, that a User belonging to the Local Group cannot do.

Having said that, even the Administrator has a God per se, that being Microsoft Windows TrustedInstaller, and / or SYSTEM, both of which can own a file or folder, and if they do, then the Administrator cannot simply modify these files or folders, unless they take ownership first.

There are a number of methods to manually do this which allow you to then make modifications you wish.

In terms of your program though its likely you have forgotten to modify your app.manifest to ensure when the Program is executed the SYSYTEM can see you are indeed a member of the Administrative Group.

You'd need to edit your Programs executable manifest and take a look at the <security> section.

Example:

Code:
<security>
   <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">

  <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

  </requestedPrivileges>
</security>

The above excerpt displays how to request Administrator access, and is needed for your program to work.

Unfortunately, the way Windows is set up even correctly modifying the Programs executable manifest may not achieve the goal of being able to delete any file or folder you want.

Each process running needs to be able to obtain Privileges in order to do its task. Based on your opening thread, it would appear a process is unable to obtain permissions to remove a file or folder, most likely because that file or folder is owned by the TrustedInstaller or SYSTEM.

You can modify your C# code to enable the replacement of ownership in these cases. To read about a way you could do this, which has some example code to review, see here:

http://processprivileges.codeplex.com/

If you feel that may help you'll need to download the ProcessPrivileges files supplied there, then make use of it in your code like so:

Code:
using (new ProcessPrivileges.PrivilegeEnabler
    (Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
    Your other coding here of course
}


Perhaps you could confirm what backedup folders you cannot delete at the moment, or right-click on them and select Properties > Security tab > click Advanced button to see what owns it at the moment.
 
Joined
Jun 6, 2016
Messages
53
Reaction score
2
I checked my account and all groups
Everyone
MOISEY2-PC\HomeUsers
BUILTIN\Performance Log Users
BUILTIN\Users
NT AUTHORITY\INTERACTIVE
CONSOLE LOGON
NT AUTHORITY\Authenticated Users
NT AUTHORITY\This Organization
MicrosoftAccount\[email address removed by Regedit32]
NT AUTHORITY\Local account
LOCAL
NT AUTHORITY\Cloud Account Authentication
--------------------------------------------------------

I do not see me like Admin - and I have admin rigths
and already in admin group

Images uploaded removed by Regedit32 as:
  1. they display your email address, and
  2. the images were duplicated
Please refrain from posting personal information.
 
Last edited by a moderator:

Regedit32

Moderator
Joined
Mar 4, 2016
Messages
3,617
Reaction score
1,139
If you do go down the path of using that third party tool mentioned previously, here is a sample of what you might code as a separate class to run with your own efforts.

Sample [ not intended to be the final code ]

Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Linq;

namespace DeleteAFolder
{
    public class ACL
    {

        internal static void SetAccessibleToCurrentUser(FileInfo fi)
        {
            var fs=fi.GetAccessControl();
            FixOwner(fs);
            fi.SetAccessControl(fs);
            FixAccess(fs);
            fi.SetAccessControl(fs);
        }

        private static void FixAccess(FileSystemSecurity sec)
        {

            foreach (FileSystemAccessRule fsar in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)).OfType<FileSystemAccessRule>().ToArray())
            {
                sec.RemoveAccessRuleAll(fsar);
            
            //    string userName = fsar.IdentityReference.Value;
            //    string userRights = fsar.FileSystemRights.ToString();
            //    string userAccessType = fsar.AccessControlType.ToString();
            //    Console.WriteLine(userName + " : " + userAccessType + " : " + userRights + "<br/>");
            //    sec.RemoveAccessRule(fsar);
            }
            string currentUser = WindowsIdentity.GetCurrent().Name;
            //sec.AddAccessRule(new FileSystemAccessRule(currentUser, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
            sec.AddAccessRule(new FileSystemAccessRule(currentUser, FileSystemRights.FullControl, AccessControlType.Allow));
            //sec.AddAccessRule(new FileSystemAccessRule(currentUser, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));

        }

        private static void FixOwner(FileSystemSecurity sec)
        {
            var sid = sec.GetOwner(typeof(SecurityIdentifier));
            var ntAccount = sid.Translate(typeof(NTAccount));

            string currentUser = WindowsIdentity.GetCurrent().Name;
            if (ntAccount.ToString() != currentUser)
            {
                ntAccount = new NTAccount(currentUser);
                sec.SetOwner(ntAccount);
            }
        }

        internal static void SetAccessibleToCurrentUser(DirectoryInfo di)
        {
            var fs = di.GetAccessControl();
            FixOwner(fs);
            di.SetAccessControl(fs);
            FixAccess(fs);
            di.SetAccessControl(fs);
        }
    }
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top