Run as Administrator in the startup [duplicate] - c#

This question already has answers here:
How to run a program automatically as admin on Windows 7 at startup?
(9 answers)
Closed 9 years ago.
hey I'm trying to launch an app on the startup I have always done it just fine by using this code :
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rkApp.GetValue("Folder Locker") == null)
{
rkApp.SetValue("Folder Locker", Application.ExecutablePath.ToString());
}
But now when I do this:
requestedExecutionLevel level="requireAdministrator" uiAccess="false"
to start as administrator the app doesn't start on the start up I need help I hope it would be a small problem and not a big deal.

You cannot get an application to run at logon that will elevate and somehow bypass the UAC dialog. That would pretty much defeat the purpose of UAC.
Your options include:
Accepting that the user will be prompted for elevation.
Modifying your application so that it does not require elevation. If some operations require elevation, then start a new elevated process to perform those tasks
Running your process as service in session 0 where UAC does not apply.

Related

How to use RegOpenKeyEx in Local System app? [duplicate]

This question already has answers here:
Updating HKEY_CURRENT_USER hive from a service
(2 answers)
Closed 4 years ago.
I have the problem with accessing "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run". Function returns result 2, that means "File not found". I'm pretty sure this happened because of Local System rights in application but don't know how to fix this.
int result = RegOpenKeyEx(registryHive, registrySubname, 0,STANDART_RIGHTS_READ | KEY_QUERY_VALUE | KEY_NOTIFY , out registryKey);
Any ideas?
UPD: I've checked this in application with current user rights and everything worked
When running as the LocalSystem account, such as in a service, you can't use RegOpenKeyEx() to open the HKEY_CURRENT_USER hive of any user account other than LocalSystem. To open the HKCU hive of another user, you need to first impersonate that user, such as with ImpersonateLoggedOnUser(), and then use RegOpenCurrentUser().

Shortcut in a System Startup is not starting up for other users but only for administrator

I have Programatically created a shortcut of my tray application in C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup.
But my tray application is not launching when i login for any user. It is only starting for the administrator.
Can someone please tell me, i have spend a complete day to solve this issue but unable to fix it..
var startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup);
var shell = new WshShell();
var shortCutLinkFilePath = string.Format("{0}\\{1}", startupFolderPath, "MyShortcut.lnk");
var windowsApplicationShortcut = (IWshShortcut)shell.CreateShortcut(shortCutLinkFilePath);
windowsApplicationShortcut.Description = "Shortcut for My Tray application.";
windowsApplicationShortcut.WorkingDirectory = assemblyPath;
windowsApplicationShortcut.TargetPath = executablePath;
windowsApplicationShortcut.Save();
I think there are a couple of ways to deal with this:
A program won't start with elevated permissions from the Startup folder (or similar "start at logon" locations), as Harry Johnston points out. But if it has an elevation manifest you should be able to relaunch it with a shell execute, then it will prompt for elevation because it's no longer directly from Startup. The Startup shortcut could have a command line option as a quick way to knows it's from Startup, then run the path to your executable with ShellExecute() or a Process.Start with a ProcessStartInfo.UseShellExecute set true. This should get the porompt for elevation which is required for elevated code to run. Caveat: I've not tried this but I've heard reports that it works.
A service can run elevated and start when the system starts. Your startup program can be non-admin and have a message protocol to ask the service to do things. This is overkill for an app you just want to run for a short time, but not for a system monitor type of app.

Forced the application to have the administrator privileges

I need to give my application administrator rights, knowing that it will be run from a user session and not admin account.
I've looked on other sites, but can't find anything that helps.
I tried editing the manifest among other things and there have inserted the line:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This gave me an error when trying to publish using ClickOnce, but not when I debug.
Can you help me?
first of all - indeed, it's not allowed by design, to install and ClickOnce app as admin: http://msdn.microsoft.com/en-us/library/142dbbz4(v=vs.90).aspx
take a look at this post: http://antscode.blogspot.ca/2011/02/running-clickonce-application-as.html -
it explains how to run ClickOnce app as admin. BUT - it have to say that I have walked this path - and I did not have much luck with it. I had numerous troubles with this approach (trying to run ClickOnce app with admin privileges). As far as I recall, the biggest problem was auto-update was not working properly. Not to mention that non-admin users might need to enter admin credentials all the time.
So my advise would be to rethink your logic, and encapsulate the piece you need to be done as admin in a separate EXE file - and make it very clear for a user that when he clicks THAT button, UAC prompt will show up (probably by addin "shield" icon to the button). And in that button_click event do something like this:
// 2. Run Photoshop action on this image (and wait for the task to complete)
if (string.IsNullOrWhiteSpace(this.PhotoshopEnhanceActionAbsPath) == false)
{
var pi = new ProcessStartInfo(this.PhotoshopEnhanceActionAbsPath, "\"" + imgPhotoshopActionAbsPath + "\"");
pi.UseShellExecute = true;
pi.Verb = "runas";
var photoshopAction = Process.Start(pi);
var success = photoshopAction.WaitForExit();
if (success == false)
{
// do something here
}
}
this approach worked very well for me. The key here is this:
pi.UseShellExecute = true;
pi.Verb = "runas";
it runs your EXE with admin right - so UAC prompt will be displayed at that moment. Another nice consequence here is that users might not run this particular piece of logic each time they are using the app - and therefore they won't be annoyed by the prompt when they do not need it.
I'm pretty sure that this behaviour is by design.
ClickOnce apps are designed to be installable without Administrator privileges. It's not possible to elevate them at runtime as this means that effectively a user with no admin rights could install then run the app as admin; this would be a security risk.

copying file to a directory(c: or c:program files) that i dont have permission [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Allow access permission to write in Program Files of Windows 7
okay, here is my code :
System.IO.File.WriteAllBytes(path1, path2);
however, there is a problem.
user(windows 7 users dont have permission to copy file to c: by default)(...i mean for programs...)
therefore, program fails.
if user gives permission to copy file in c: program works fine. but you cant tell every user " go to permission.........." so how can i make something to allow user that i copy my file to c://
You may add the Application Manifest File in your project by Selection Add New Item. Update the requestedExecutionLevel to
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This way user will be asked that the application needs to run in Administrative mode. Hope this help.
Your application shouldn't be writing to the C drive. Only users with permission, or administrators, can grant an application to do that. Instead, try writing to folders that aren't limited by tight security. You can see some of them here.
You can't. You have to give the user permissions.

Write Access to Program Files folder

my application include a self-updater executable that is used to update the application.
One of the first steps the updater is performing is to check that it does have write permission to the application folder
IPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, _localApplicationCodebase);
if (!SecurityManager.IsGranted(perm))
{
OnProgressChanged("Security Permission Not Granted \n The updater does not have read/write access to the application's files (" +
_localApplicationCodebase + ")",MessageTypes.Error);
return false;
}
OnProgressChanged("Updater have read/write access to local application files at " + _localApplicationCodebase);
return true;
When executing under Win7/Vista, this code pass (meaning that according to CAS, the code does have write access), however when I try to write files, I got an Access Denied (and I confirmed that the files are NOT in use)
I understand that Vista/Win7 UAC is preventing users from writing files in the program files folders. However, what I don't understand is why the permission is granted if in reality it is not
Regards,
Eric Girard
PS : If I run the same code using 'Run As Administrator', it works fine
The important thing to know about UAC is that by default, no code runs with Administrator privileges and thus cannot write to the Program Files directory. Even if you are logged in as an administrator, the apps are launched with standard user privliges.
There are two ways around this. You can have the user start the app with the Run As Administrator menu item. But this relies on the user to remember something. The better was is to embed a manifest into your executable that requests administrator privileges. In the manifest, set requestedExecutionLevel to requireAdministrator. This will cause UAC to prompt the user for admin credentials as soon as the app starts.
As Daniel said, the best solution is to put the updating functionality in a separate application. Your primary app will have an manifest that sets the requestedExecutionLevel to "asInvoker" and your updater app with request "requireAdministrator". Your primary app can run with standard privileges. But when the update needs to happen, use Process.Start to launch the updater application that requires the user to enter the admin credentials.
The best way to write an auto updater is to have a secondary application. The first program calls the second with elevated privileges, prompting UAC. Then the second application can install the patches.
I'm not sure if this is what you're trying to do, but I've found this post helpful. The included code let's you detect if you're app is running on Vista, if UAC is enabled and if user is elevated.
http://www.itwriting.com/blog/198-c-code-to-detect-uac-elevation-on-vista.html
then restart your app with runas to let user elevate permissions
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.FileName = Application.ExecutablePath;
Process.Start(processInfo);

Categories