Problems
- 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
- Try & Catch: Using either one of these methods(Exception, UnAuthorizedAccessException, Blank Catch, continue)
Questions
- 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());
}
}
}
}
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
For more read here: http://midnightprogrammer.net/post/How-To-Build-UAC-Compatible-Application-In-NET.aspx