How to handle UnauthorizedAccessException from User Code - c#

In a Windows Application I have, I am doing some changes in registry like deleting a particular key, in some test scenarios like in a Vista machine with its UAC put on, I'm getting System.UnauthorizedAccessException. My code would look something like this:
try
{
//delete registry keys
}
catch (UnauthorizedAccessException ex)
{
//handling
}
catch (Exception genEx)
{
//handling
}
But the application would still go crashing., not being handled by the catch block. Is there some way I could handle it?

You're probably throwing another exception from the catch block.
Try commenting all lines in the catch block and it should work just fine.

Most common and obvious reason is that the path / file program is trying access doesn't have access to the identity under which its running.
Read more here on MSDN

you have to set admin access for your application
for that just right click and select properties
and check Run as Administrator check and run your application
to run as administrator for all users click on all user button and select run as administrator for all users this will always run your application with admin access for all users

Related

Find out if another application is running as admin

I'm trying to determine if another application is running as an administrator. There are 100's of SO questions about finding if your application is or not, but not for another application.
If I do var processes = Process.GetProcesses(); and loop through them, they don't appear to have any "Elevated" or "IsAdministrator" properties on them. I also found a function on here to get the Owner but they all come back as "My-Laptop\Me" so that's not working for me the way I hoped it would.
Is there a way to find this? I'm on Win 8.1 and would prefer something that works for 7 as well, but if it only works for 8.1+ that's totally fine.
Thanks!
EDIT:
My application has to run as an administrator.
You can use the technique from this answer, just replace Process.GetCurrentProcess().Handle with the Process.Handle of the other process.
If you look at the code (there's quite a bit of code there) it get the process "user token" (the permissions the process is running under) and checks if this token has the administrator role or not,
Assuming your process is not running as administrator, trying to get information about a process that is elevated via UAC (such as its MainWindowTitle) will throw an AccessDenied exception, where a non-elevated process will permit you access to that information. This assumes you also verify the owner of the process to check that it's you.
try
{
var foo = process.MainWindowTitle;
return false; //Process is not elevated
}
catch (Win32Exception ex)
{
return true; //Process is elevated if ex error code is AccessDenied
}

Know whether the file or directory having permission to delete it in c#

In my application, I'm trying to delete file from code behind but it throws the error called "accessed denied". Anyone can tell me that how to get whether the file is having delete permission or not.
Thanks in advance
You can just handle the exception
try
{
Directory.Delete(dirPath);
}
catch (UnauthorizedAccessException ex)
{
//Access denied
}
If you try to find out before calling Directory.Delete there's a small chance that there's a race condition and something locks the directory which would cause your program to throw an exception. If this exception isn't handled the program will be in an unstable state.

Check if I have write access to folder in Silverlight 5 Out of Browser Elevated Trust

How can I check in a Silverlight 5 OoB Application with Elevated Trust if I can write in a certain user-selected folder?
At the moment I attempted to create and delete a folder, if no exception occurs I have write access.
try {
CreateSubDirectory(path, newDir);
DeleteSubDir(path, newDir);
writeAccess = true;
} catch(Exception) {
writeAccess = false;
}
I searched in the documentation and didn't found any less hacky way of doing it. How do you recommend?
Thanks!
From what I've found, you don't have much choice, try/catch is the way to go.
But you should catch with much more precision. You want to be able to tell between IOException, SecurityException and other exceptions.
You can do a check to see if your app has elevated privileges.
if (Application.Current.HasElevatedPermissions)
{
// Do File IO here
}
These articles have some more information:
How to: Access the Local File System in Trusted Applications
Trusted Applications

C# Windows Service Textwriter

I've created a standard windows service that uses the LocalSystem account. For the log files I use textwriter to write to a specified file within C:\Users\useraccount directory. The problem is, when running as a service under LocalSystem, it doesn't want to create or write to the file at all.
string dir = #"C:\Users\useraccount\log.txt";
StreamWriter sw = File.AppendText(dir);
As you can see, the directory is hardcoded in so there isn't any base directory conflicts seeing as LocalSystem would start in System32 or something of that nature. The permissions on the folder lets the System account access it fully (windows 7) so why am I not able to create/write to that file?
Thanks for any input!
Edit:
Apparently the logging program thread is running as LocalSystem as well, when I really need it to be running as a standard user. So how do I execute a threaded process from the service to run under the local user account instead of under LocalSystem.
I use Thread.new(process) where process is an additional program. The process program needs to receive input before it writes anything, and it isn't receiving input because it's on the wrong account. How would I fix this?
Should do the same trick as using(...) but did you try:
sw.Close();
Without it there's just an empty file but it throws no exceptions..
Try this code and check what exception reports:
try
{
using (StreamWriter sw = File.AppendText(dir))
{
sw.WriteLine("test");
}
}
catch (Exception ex)
{
Debug.Print(ex.Message);
}
Just a note: it's a good idea to use using(...) with all classes implementing IDisposable interface, so you can be sure they are freed when exiting block!
First of all I would use Log4Net instead of rolling your own logging mechanism, unless there is a good reason not to. This way you can create the log file you want but also (via a config or code) add log appenders such as windows event log. Then I would make sure I log any and all exceptions. You say no exception is being thrown, I expect there is an exception being thrown on the logging thread which is not 'bubbling' up, so catch it and log it (Log.Error(ex)). You can then see these exceptions in your event log if you have configured an event log appender.
Lastly, I'm not sure how you would assume the security context of the logged on user. Sounds like that would be a big securtity hole, unless you write something that prompts the user to enter their credentials or grant the process the right to impersonate/assume the user security context.. Perhaps that is the answer, the service responds to a user logon by prompting the user to grant this right. I'll have a look around for a better answer to this point.

xbap gracefully handle lack of permissions

I have an Xbap application that is part of an intranet application that needs file system access.
Ive made the app full trust, signed it with a valid certificate and imported the cert into ie and the xbap works perfectly.
My issue is that I want to gracefully handle a Permission Denied exception if the user doen't have the certificate installed, ie does not have File system IO access
I thought I could achieve this by running the xbap in partial trust mode and using something like the following to test for permissions
CodeAccessPermission p = new FileIOPermission(FileIOPermissionAccess.Write, #"c:\newfile.txt");
try
{
p.Demand();
// Has access
}
catch (Exception ex)
{
// Does not have access
}
The issue is however that the above code will always fail if you have not added the FileIOPermissions permission to the "Permissions required by the application" list in the security tab of your project's properties window... even if run from your local file system instead of through a web server.
BUT
If i do add the FileIOPermissions permission, and the user does not have the certificate installed, none of my code is ever hit and the xbap throws a generic "Trust Not Granted" error screen... which i dont want, i want to show my users a proper error screen that explains what they can do to fix this error
any ideas?
You can manually edit the app.manifest file to request lower minimum permissions for your application, and then (in theory) you testing code will not always fail when you ask for the file permission, but as intended will fail only when user has not granted your code the required permissions.

Categories