SetAccessControl() issues this: Attempted to Perform An Unauthorized Operation

MARK ROCKMAN 1 Reputation point
2021-01-27T22:52:48.03+00:00

I am a guy who designs and codes programs for Windows 10 desktops. I am puzzled by the error message. How do I work around the complaint from Microsoft's software? How can I make my code authorized?

public static void RemoveAllACEsFromDirectory(string directory)

    {

        try

        {

            string tabs = "\t";

            System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(directory);

            System.Security.AccessControl.DirectorySecurity dSecurity = dInfo.GetAccessControl();

            System.Security.AccessControl.AuthorizationRuleCollection acl = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

            foreach (System.Security.AccessControl.FileSystemAccessRule ace in acl)

            {

                if (ExtensiveReporting)

                {

                    Console.WriteLine("{0}Account: {1}", tabs, ace.IdentityReference.Value);

                    Console.WriteLine("{0}Type: {1}", tabs, ace.AccessControlType);

                    Console.WriteLine("{0}Rights: {1}", tabs, ace.FileSystemRights);

                    Console.WriteLine("{0}Inherited: {1}", tabs, ace.IsInherited);

                    Console.WriteLine();

                }

                try

                {

                    dSecurity.RemoveAccessRule(new System.Security.AccessControl.FileSystemAccessRule(ace.IdentityReference, ace.FileSystemRights, ace.AccessControlType));

                }

                catch (Exception F0xxx)

                {

                    Console.WriteLine("Exception:  System.Security.AccessControl.FileSystem.RemoveAccessRule()");

                    Console.WriteLine(F0xxx.Message);

                    Console.WriteLine("Directory:  " + directory);

                }

                try

                {

                    dInfo.SetAccessControl(dSecurity);

                }

                catch (Exception F1xxx)

                {

                    Console.WriteLine("Exception:  System.IO.DirectoryInfo.SetAccessControl()");

                    Console.WriteLine(F1xxx.Message);

                    Console.WriteLine("Directory:  " + directory);

                }

            }

        }

        catch (Exception e1)

        {

            Console.WriteLine("RemoveAllACEsFromDirectory:  Could not access {0}", directory);

            Console.WriteLine(e1);

        }

    }
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,135 questions
{count} votes