Getfiles() UnAuthorizedAccessAcception in WIN7 - c#

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

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.

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

Related

Why is access denied when I try to move a directory?

I have two directories: folder1 and folder2. folder1 contains a file. I'd like to move folder1 under folder2 to result in folder2\folder1. When I try to do this with the C# code below, I get:
System.IO.IOException: Access to the path 'E:\www\dev\test\MoveDirectories\folder1' is denied.
The relevant code:
// In Page_Load.
MoveDirectory("folder1");
// Method for moving directories.
protected void MoveDirectory(string strMoveThis)
{
try
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Server.MapPath(strMoveThis));
dir.MoveTo(Server.MapPath("\\folder2\\"));
}
catch (Exception ex)
{
Response.Write(ex);
}
}
My ASP.NET 4.0 app pool has modify privileges on the folder1. This is actually a test application with code that has been pulled from a much bigger application, so it doesn't have all of the testing and exception handling one would expect.
EDIT: I found that I can create files within folder1.
I hate to answer my own question, but...
Basically, I updated this:
dir.MoveTo(Server.MapPath("\\folder2\\"));
to this:
dir.MoveTo(Server.MapPath("folder2\\" + strMoveThis));
Same permissions, but a better formation of the path. Thanks for your help, everyone!

Access is denied in windows forms

Iam asking this question as a series to the below link
Unable to delete .exe file through c#
While i was debugging the application,iam able to delete the .exe file.But when i try to delete the application after installing in the desktop,again iam getting the exception message as "Access is denied".
Edit:-
The code i am using to delete the file
public bool deleteAppExecutable(string filePath)
{
try
{
if (File.Exists(filePath))
{
var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
di.Attributes &= ~FileAttributes.ReadOnly;
SetAccessRule(filePath);
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);
File.Delete(filePath);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public static void SetAccessRule(string filePath)
{
FileInfo dInfo = new FileInfo(filePath);
FileSecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Delete, AccessControlType.Allow));
dInfo.Refresh();
dInfo.SetAccessControl(dSecurity);
}
I found the solution why i am getting the "access is denied" exception in my application.
Since i am deleting a file inside the application through code i need to have the privilege of "Administrator".
One way is to make the user login manually as administrator.But that is not a better option.
Another way is to create an App Manifest file within your project and set the level as "administrator."
Creating App Manifest--> Right click on the project->Add new item-->Select App Manifest option from the right pane->Click ok
Open the manifest file and change the level to "requireAdministartor".
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will solve the issue while running the application,it will prompt user to run as administrator.
Hope this will be helpful to someone in future. :)
Check that you have full permissions on the folder the exe is contained in (and all of it's child objects)

C#, Creating .txt file

I am having trouble creating a .txt file with the code below. I get an exception as follows:
Unhandled exception: System.unauthorizedAccessException: Access to the
path 'C:\log.txt' is denied.
I have looked online and done similar things to what is on the api. Below is my code, so you can understand what my train of logic is. What do you think causes this exception? Thanks in advance!
static StreamWriter swt;
static string logFile = #"C:\log.txt";
static FileStream fs;
static void Main(string[] args)
{
Console.Out.WriteLine(swt);
string root = args[0];
if (!File.Exists(logFile))
{
try
{
fs = File.Create(logFile);
}
catch (Exception ex)
{
swt.WriteLine("EXCEPTION HAS BEEN THROWN:\n " + ex + "\n");
}
{
}
}
}
You're most likely getting this error because a standard user cannot write to the root of a drive without elevated permissions. See here.
Detect the folder permissions. It has to has write permission on the logged user.
Yes, it is permission error. You don't have enough rights to write file in C: drive. To write in these types of folder/drive you need admin permission.
You can give your application admin rights. Simple way is enforce your application to start in admin account/rights only. To achieve this
Solution Explorer -> your project -> Add new item (right click) -> Application Manifest File.
In this file change requestedExecutionLevel to
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
These enforce your application with admin rights only. On Windows 8/7/Vista it will display UAC (User Access Control) dialog box when you start the application.
Hope this will help you....

C# - Cannot access all files

My application uses the .NET object Directory.GetFiles()
The actual overload I'm using is
var allFiles = Directory.GetFiles("C:\\Users\\Dave", "*.*", SearchOption.AllDirectories);
The issue is when the source folder is C:\Users\UserName as it then tries to look through application data folder.
When it tries to read from the application data folder, an exception is thrown:
"Access to the path 'C:\Users\Dave\AppData\Local\Application
Data' is denied."
So, my question is does any one have an opinion as to my options? I would assume I have to either change the way I collect all the files or, there may be a built in overload or method which will allow me to continue this (which I clearly don't know about).
If it helps, the goal of this is to take all the files retrieved by Directory.GetFiles() and 'paste' them else where (a glorified copy and paste/back up). I'm actually not too worried about system files, just 'user files'.
The directory %AppData% is a system-protected directory. Windows will try to block any access to this directory as soon as the access was not authorized (An access from another user than the Administrator).
Only the Administrator by default has privileges to read and write from/to this directory.
Alternatively, you can catch the exception and see if the result is Access Denied. Then, you may prompt the user to run as an Administrator to complete this step. Here's a simple example to prompt the user to run as Administrator
try
{
var allFiles = Directory.GetFiles("C:\\Users\\Dave", "*.*", SearchOption.AllDirectories);
}
catch (Exception EX)
{
if (EX.Message.ToLower().Contains("is denied."))
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Application.ExecutablePath;
proc.Verb = "runas"; //Required to run as Administrator
try
{
Process.Start(proc);
}
catch
{
//The user refused to authorize
}
}
}
However, you may always prompt the user to authorize when your application launches which is NOT always RECOMMENDED. To do this, you'll have to edit your project app.manifest file
Locate and change the following line
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
to
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Thanks,
I hope you find this helpful :)
It is better to use a foreach loop to get the folder names that you can acces:
DirectoryInfo dI = new DirectoryInfo(#"C:\Users\Dave");
List<string> files = new List<string>();
foreach (DirectoryInfo subDI in dI.GetDirectories())
{
if ((subDI.Attributes & (FileAttributes.ReparsePoint | FileAttributes.System)) !=
(FileAttributes)0)
continue;
files.Add(subDI.FullName);
}

Running an app using process.start returns different value than running it manually

I'm running a tool that samples the HW PCI for a specific value (I didn't write it).
When I run it from the command prompt, it returns one exit code (the correct one) but when I run it from another application using Process.Start, it returns another exit code.
Is there a difference between running an application directly or via Process.Start?
Do you know of a simple workaround for this issue?
As stated in Hassan's answer (which solved my similar issue), the exit code returned from Process.Start() is affected by the location of the executable, in particular which directory it is located in. Here's the code I used:
string yourExe = "C\\Program Files\\Your Directory\\YourExe.exe";
string currentDir = Directory.GetCurrentDirectory();
string yourExeDir = "C\\Program Files\\Your Directory";
try
{
Directory.SetCurrentDirectory(yourExeDir);
}
catch (DirectoryNotFoundExeption dnfe)
{
MessageBox.Show("The specified directory does not exist. " + dnfe.Message);
}
if (!File.Exists(yourExe))
{
MessageBox.Show("Can't find yourExe");
}
else
{
Process.Start(yourExe);
}
try
{
//Set the current directory.
Directory.SetCurrentDirectory(currentDir);
}
catch (DirectoryNotFoundException dnfe)
{
MessageBox.Show("The specified directory does not exist. " + dnfe.Message);
}
This switches the current working directory to the directory where the .exe is located, runs it, and then switches back to whatever your previous working directory was.
If you want the same result from Process.Start(), you have to execute your application on
the same working directory as your command line.

Categories