c# winforms Application, run a cmd command as system - c#

I have written a program in the last days which automatically changes the proxy server. This runs as a Windows Forms Tray Application on the user level.
Now came a request which caused me some problems. A cmd command "ipconfig /registerdns" should be executed but this requires higher permissions.
I'm now looking for a way to easily execute this command in normal user context. Is there a way to run this one command as a system? Or any other possibility?
Or is there another function to re-register the dns without admin priviledge?
I hope there is a easy way.
Thank you very much!

As i know admin processes can only be created by another admin processes but still you can try adding this parameter to your process's start info
StartInfo.Verb = "runas";
if it doesnt work you set your application to run always as admin by adding app.manifest to your project and editing line 19 as below.
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Create a script (.cmd or .bat) containing required command (here: "ipconfig /registerdns"), then flag it as "Run as administrator". Finally, run this script from your app instead of original command.
This should help in flagging as "Run as administrator": How to code a BAT file to always run as admin mode?

Okay so I found no solution for my former problem, because it is not possible to launch a elevated command from a user Application. But I found a powershell command: Register-DnsClient. This command does the same and does not need elevated priviledges. Only downside is it works only on Windows 8.1 and newer. So Windows 7 is not supported.

Related

Build Events, permission when run a script

I have a .bat script with I configure to run in my post-build event call $(ProjectDir)scripts\install.bat, this script to install a service in my local machine.
When I open a cmd and run as administrator, this script works, but if I run in normal cmd doesn't work. Exist some way I run call $(ProjectDir)scripts\install.bat in administrator mode in visual studio in post-build event command line or someone other way to script works in normal command line.
Note: I have administrador privileges
Assuming this is Windows 7 or later:
Even though you have administrator privileges on the machine, you still need to run Visual Studio with administrative privileges to do things that a normal user can't do, because of UAC. Right-click on your VS icon, and select "Run as Administrator".
Maybe a few years too late, but here is the solution for anyone still searching.
Just add this to the top of your batch file and it will ask UAC for admin rights before executing the rest of the script.
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)

Can I set the properties of an exe file via C#?

I am using Unity to build my game. I need the application to always run as administrator.
When I build my game, I right click on the exe that is produced and set 'Run this program as an administrator' on in the Compatibility > Settings section of the exe properties.
I can write an editor script (C#) that'll execute after a build has completed. So I was wondering if I could automate this step so that I do not forget to do it every time I build?
I'm not sure if this solves your issue.
But you could add an "Application Manifest File" and configure:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
With this configuration the user gets always a UAC promt.
Do not have a ready made solution but i can give you an idea:
Have a look at this, using this way you can check if your application is running as an administrator, if no, it starts another process with administrative privilege and you can later call:
Application.Quit();
to terminate the current instance.
Other than this you must have to wrap this code under platform dependent compilation.
I know it is not a best solution, but can fix this issue.
Hope it helps!

Start WPF Application with RunAs Prompt

So I have a WPF application and here is what I want it to do. I can right click on the executable, select Run As Different user, and get the Windows Security box with User Name and Password, as well as the Smart Card logon. I was wondering if there was a way to launch the Sysinternals Run as Different User to come up automatically, without having to right click and select Run As Different User. Any thoughts?
I was able to go into the Assembly Manifest and force it to run as administrator, but that isn't what I need. I really need the option to run it with Smart Card credentials. Thank you in advance!
AFAIK, the only way to do it that works is by using the RunAs exe as follows. The /savecred will cache credentials, but your user will still have to enter it the very 1st time (which might be annoying for your use-case).
runas.exe /savecred /user:<localmachinename>\administrator "path to your WPF exe"
or, if you're on a domain:
runas.exe /savecred /user:<DomainName>\<AdministratorAccountName> "path to your WPF exe"
Example: To Run Visual Studio 2012 in Admin Mode, I tried the following and it worked. I was prompted to enter my password just once, for the 1st time.
runas.exe /savecred /user:<My_DomainName>\<My_AdministratorAccountName> "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe"
Further Reading: Runas Documentation.

How to run application as administrator in debug with Visual Studio?

I have a c# application where I have to have read/write access to the root of the C drive. I realize I can compile the code and run the executable as administrator and it works. But I need to debug it and I am unsure as to how one would start the app within Visual Studio.
I have tried adding:
<requestedExecutionLevel level="asInvoker" uiAccess="true" />
to my manifest but I still get access denied error.
Here is the line of code that fails:
MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(#"c:\somemapnamefile.data", System.IO.FileMode.OpenOrCreate, "somemapname", 1000);
For now I have a work around but I'd like to know for the future.
Just run visual studio itself as an administrator. Any program you debug from there will also be run as an administrator.
VS must be run with admin right. however, a more elegant way is in the requiredExecutionLevel in manifest should set to 'requireAdministrator'.
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
When you open the project and try to debug, the VS2012 will warn about the admin right and restart itself to admin right. And also the exe file will be marked as requiring admin right at the first place therefore when deploy you don't need to configure admin right requirement in file properties.
You can also set this administrator option automatically:
To answer the question in your title, you can just select Run as Administrator from the context menu when starting VS.
Now the checked answer will not working.
You should find an option for this in project properties Linker -> Manifest File -> UAC Execution Level. Set this to requireAdminstrator.
This will cause the default generated manifest to include the requestedExecutionlevel that you need, so that your users will be prompted automatically to elevate their privileges if they are not already elevated.
The "This task requires the application to have elevated permissions" error occurs because of The current user didn’t have a sufficient privilege to open Visual Studio.
As a temporary solution
You can overcome this issue by right-clicking on visual studio and select run as administrator at every time you intend to open it
As a permanent solution,
You can check the compatibility troubleshooting
Right, Click on Visual Studio > select Troubleshoot compatibility.
Select Troubleshoot Program.
Check The program requires additional permissions.
Click on Test the program.
Wait for a moment until the program launch. Click Next.
Select Yes, save these settings for this program.
For the detail steps with images, please check Visual Studio requires the application to have elevated permissions

Install msi with msiexec and c#

What is the best way to install a .msi in a c# application in silent mode. I want to install a .msi file using msiexec, but I don't know how to do this. The problem is for using msiexec with /qn, you have to run it in a cmd.exe process start "as a administrator" and I don't know how to accomplish something similar with a c# application (for more details, a wpf project in VS 2010). The best I come to is :
Process p = new Process();
p.StartInfo.FileName = "runas.exe";
p.StartInfo.Arguments = "/user:Administrator cmd";
p.Start();
A windows will pop and ask for a password, but I found this behavior pretty ugly. I mean, I don't want to ask the user for his password. Is there anyway way to start my project, set it as a kind of "run as administrator" (the UAC will pop-up, but that's ok) and just run the msiexec command ? Or is there any other way to make a silent install of a .msi file ?
Thank you
Despite somebody voted down without comment, this is a very thorough answer IMO:
Maybe somebody misunderstood, because the answer is quite long.
Recommendation for short reading: Take option 2) .
First, generally, try to avoid RunAs as often you can. With RunAs you are creating a mixed user situation which is not supported by all scenarios and applicatons/processes. With operating systems newer than XP it is not really necessary. Requiring admin rights with UAC (e.g. the correct manifest in the .exe) is at least MS recommendation !
(Just a security remark: Most secure way is still having the admin account completely separated so that neither RunAs nor UAC are normally needed.)
1) The most easy (but not my recommended) method to assure admin rights for a MSI install is doing nothing and let UAC work.
If the MSI needs admin rights, UAC will normally come up itself after some time (not every part of the install process needs admin rights, so it will take some time.
To ensure, that UAC requests come up in child processes, kinda UAC-inheritance, you have to use ShellExecute in the baseline. This is a Windows thing, has nothing to do with MSI or C#.
In C# you can do this like this:
ProcessStartInfo startInfo = new ProcessStartInfo(exeFile, arguments);
StartInfo.UseShellExecute = true;
This is of not much use, if you want a silent installation with no installation dialog (e.g. "/qn") at all.
Moreover the UAC so late has small disadvantages, so the following is recommended and very much safer:
2) Admin rights from the beginning, e.g. in the bootstrapper .exe:
If it is sure, that a setup should be started, or in general, your app needs admin rights for it's own or child processes, the best idea ist to assure, that your app itself has already admin rights from the beginning.
In other words, UAC comes up when starting the app. Then your child processes have admin rights too, and it works also for CreateProcess-type child processes and not only for ShellExecute-type.
To achieve this, just add a manifest to your app containing the following line.
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
How to do it?
Given the fact that the whole Windows 7 evangelism was based on manifests ("What is the sense of life? Giving applications a manifest."), Visual Studio in it's different versions of the last years has not really done an excellent job of supporting this. Every version is different, and it is different for C#, C++, VB apps.
For VS 2010 and C# the way to go is:
(For VB.Net, it's in 'View Windows Settings' in the solution's Application tab, I've read here.)
In Solution Explorer, right click on the project and select "Add New Item", "New element" and choose "Application Manifest File".
Open this in VS by clicking and you will find the existing node of together with comment lines describing the alternatives. If you don't know about them, it is a good point of googling to learn one of the most important things about modern Windows.
Change the line so that level="requireAdministrator" is configured, and you are done. Your app now needs elevated rights. Try out after build.
(The "uiAccess" attribute, you can ignore, until your app shall control/automate the UI of other apps like in a remote control or UI testing app.)
Start the MSI install normally with "msiexec.exe ...". Don't forget the quotes at the right places and to catch the return code for errors and reboots.
An alternative to msiexec is using the MSI API (socalled external UI), but it is more complicated.
3) No admin rights at all. Unfortunately this is not possible or would break security policies for standard applications which should be installable machine-wide in the programs directory. There is a lot more to say to this in detail of course.

Categories