Starting a Windows application using a specific user account

I need to make sure that my widnows (winform not console) application runs under a specific user account (in other words, any user can log in, but the exe file will always run as the specified user).

Can this be done programmatically? If so, how?

+3
source share
2 answers

You can run the application as follows:

ProcessStartInfo psi = new ProcessStartInfo(myPath);
psi.UserName = username;

SecureString ss = new SecureString();
foreach (char c in password)
{
 ss.AppendChar(c);
}

psi.Password = ss;
psi.UseShellExecute = false;
Process.Start(psi);
+4
source

One thing you can do in your application is to check if you are working as the right user, and if not, create a new instance of your application as that other user. The first instance will then exit.

, , , .

CreateProcessWithLogonW, LOGON_WITH_PROFILE. , , , .

EDIT: , , .NET, :

, . WindowsIdentity System.Security.Principal. GetCurrent WindowsIdentity , . Name , .

ProcessStartInfo LoadUserProfile = true, FileName, , Arguments, UserName Password, , Domain UseShellExecute = false. Process.Start(), ProcessStartInfo.

, , # :

using System;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;

// Suppose I need to run as user "foo" with password "bar"

class TestApp
{
    static void Main( string[] args )
    {
        string userName = WindowsIdentity.GetCurrent().Name;
        if( !userName.Equals( "foo" ) ) {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "testapp.exe";
            startInfo.UserName = "foo";

            SecureString password = new SecureString();
            password.AppendChar( 'b' );
            password.AppendChar( 'a' );
            password.AppendChar( 'r' );
            startInfo.Password = password;

            startInfo.LoadUserProfile = true;
            startInfo.UseShellExecute = false;

            Process.Start( startInfo );    
            return;
        }
        // If we make it here then we're running as "foo"
    }
}
+1

All Articles