0

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?

Omegacron
  • 206
  • 3
  • 15
  • Check this answer http://stackoverflow.com/questions/2532769/how-to-start-a-process-as-administrator-mode-in-c-sharp – Jan Zahradník Jan 20 '15 at 16:36
  • there are plenty of examples on the web on how to do this are you familiar with `ProcessStartInfo` Class .. here you can call a method that you would create called RunUnderSpecific User for example.. then pass the username and password to the ProcessStartInfo Object..[Launch a Process under different users Creds](http://stackoverflow.com/questions/6413900/launch-a-process-under-another-users-credentials) – MethodMan Jan 20 '15 at 16:36
  • @MethodMan - you'd think so, but after four google searches all I could find were references to running as administrator (rather than a specific account), or finding the current user identity. That second link you provided looks promising, though - I'll try that. Thanks! – Omegacron Jan 20 '15 at 16:41
  • sometimes it's just entering the correct key word(s) or order of the word in Google.. I always qualify my searches in Google in regards to `C#` something like this 'C# Run Command Prompt from Different User` any way you're welcome and good luck.. :) – MethodMan Jan 20 '15 at 16:45

1 Answers1

2

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);  
        }
    }
}
Xaruth
  • 4,034
  • 3
  • 19
  • 26
  • 1
    I get message as The Process object must have the UseShellExecute property set to false in order to start a process as a user. – ProgSky Sep 22 '17 at 01:41