Reputation: 218
I have a console app I've built in VS2012 using C#. The EXE is located on a shared drive and can be run by any user, but I always want the EXE to run using a specific system account we have setup in AD. Essentially, I want to programmatically imitate right-clicking the EXE and doing "Run As..." instead of running under the current user who started it.
How can I force my code to always run under a specific account/password?
Upvotes: 1
Views: 4505
Reputation: 4104
I wrote this for one of my app. Hope it can help you ;)
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// Launch itself as administrator
ProcessStartInfo proc = new ProcessStartInfo();
// this parameter is very important
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().Location;
// optional. Depend on your app
proc.Arguments = this.GetCommandLine();
proc.Verb = "runas";
proc.UserName = "XXXX";
proc.Password = "XXXX";
try
{
Process elevatedProcess = Process.Start(proc);
elevatedProcess.WaitForExit();
exitCode = elevatedProcess.ExitCode;
}
catch
{
// The user refused the elevation.
// Do nothing and return directly ...
exitCode = -1;
}
// Quit itself
Environment.Exit(exitCode);
}
}
}
Upvotes: 3