Getfiles() UnAuthorizedAccessAcception in WIN7

2019-08-05 09:43发布

Problems

  1. UnAuthorizedAccessException: When searching a directory recursively such as C:\
    A "Access to the path 'c:\Documents and Settings\' is denied." Occurs even with UAC Priveledges upgraded & Administrator group access.

Attempted Methods

  1. Try & Catch: Using either one of these methods(Exception, UnAuthorizedAccessException, Blank Catch, continue)

Questions

  1. How do you handle this kind of exception and continue running your program as normal? This needs to work both on non-admin and administrator accounts.

Example Code

using System;
using System.IO;

namespace filecheck
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            int html = 0;
            try
            {
                string[] filePaths = Directory.GetFiles(@"c:\", "*.html", SearchOption.AllDirectories);

                foreach (string files in filePaths)
                {
                    if (Convert.ToBoolean(files.IndexOf("html")))
                    {
                        html++;
                    }
                    Console.WriteLine(files);
                    i++;

                }
                Console.Write("# Files found: {0} Html: {1)", i, html);
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());

            }

        }
    }
}

2条回答
狗以群分
2楼-- · 2019-08-05 10:02

To get your program working with both admin and non-admin users you either need to impersonate the user or re-build your application to "Run as Administrator" every time it is being executed or used by any user. To build this kind of application you need to add app.manifest file to your project and un-comment the following line of setting in app.manifest

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

For more read here: http://midnightprogrammer.net/post/How-To-Build-UAC-Compatible-Application-In-NET.aspx

查看更多
淡お忘
3楼-- · 2019-08-05 10:17

Unfortunately the only way to handle this is by doing the recursion manually. Even in Microsoft's own sample code they do it this way, just to avoid that the whole search fails because one or more directories can not be accessed.

So in other words, only use SearchOption.AllDirectories when you're searching a limited subset of directories which you're certain won't contain any directories which you won't have access to.

查看更多
登录 后发表回答