Access denied on subFolders of windows in C#

I need to search few files under C:windows folder but I am getting error on lots of folders like "Access denied".

I am admin on the system and I also tried running visual studio as administrator but nothing helped.

here is my code…

var exes = File.ReadAllLines("ListOfExes.txt");
            var output = new Dictionary<string, string>();
            var sb = new StringBuilder();
            var seachLocation = @"c:windows";

            FileIOPermission FilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, seachLocation);

            try
            {
                FilePermission.Demand();
                FilePermission.Assert();

                foreach (var exe in exes)
                {
                    string[] files = Directory.GetFiles(seachLocation, exe.Trim(), SearchOption.AllDirectories);
                    if (files.Length > 0 && !output.ContainsKey(exe.Trim()))
                    {
                        foreach (var f in files)
                            Console.WriteLine(f);
                    }
                }
                CodeAccessPermission.RevertAssert();
            }
            catch (SecurityException)
            {
                Console.WriteLine("You do not have permission to read this directory.");
            }

my code works fine on any other folder except windows one.
If I go to the path for access denied using windows explorer then it gave me a prompt for access and if I click on continue then it let me go inside the folder.

I understand this is happening because security design but is there any way to make search in entire windows folder if I have admin rights.
I need to use the code as I have thousands of file to search and note their path in windows directory.

Using windows explorer

error message

Source: Windows Questions

LEAVE A COMMENT