Getfiles() UnAuthorizedAccessAcception in WIN7

て烟熏妆下的殇ゞ 提交于 2019-12-11 09:00:48

问题


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());

            }

        }
    }
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4814112/getfiles-unauthorizedaccessacception-in-win7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!