Why does Process.Start throw a Win32Exception when using different user credentials?

I need to start the process as another user, and he is bombing.

I reduced it to my code to a simple reference example. This code works great to start the process itself:

        var info = new ProcessStartInfo("notepad.exe")
                       {
                           UseShellExecute = false,
                           RedirectStandardInput = true,
                           RedirectStandardError = true,
                           RedirectStandardOutput = true
                       };

However, if I add the values UserNameand Password:

       var info = new ProcessStartInfo("notepad.exe")
                       {
                           UserName = "user",
                           Password = StringToSecureString("password"),
                           UseShellExecute = false,
                           RedirectStandardInput = true,
                           RedirectStandardError = true,
                           RedirectStandardOutput = true
                       };
        Process.Start(info);

It bombs a very useful System.ComponentModel.Win32Exception message:

A service cannot be started either because it is disabled or because it does not have any associated devices with it.

Just in case, this is a safe string conversion method:

    private static SecureString StringToSecureString(string s)
    {
        var secure = new SecureString();
        foreach (var c in s.ToCharArray())
        {
            secure.AppendChar(c);
        }
        return secure;
    }

Any ideas or alternative solutions would be greatly appreciated!

+3
source share
2 answers

Secondary Logon , , ?

+5

, , , Domain ProcessStartInfo.

, :

Imports System
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Security

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;

public class Example
{
    public static void Main()
    {
        // Instantiate the secure string.
        SecureString securePwd = new SecureString();
        ConsoleKeyInfo key;

        Console.Write("Enter password: ");
        do {
           key = Console.ReadKey(true);

           // Ignore any key out of range.
           if (((int) key.Key) >= 65 && ((int) key.Key <= 90)) {
              // Append the character to the password.
              securePwd.AppendChar(key.KeyChar);
              Console.Write("*");
           }   
        // Exit if Enter key is pressed.
        } while (key.Key != ConsoleKey.Enter);
        Console.WriteLine();

        try
        {
            Process.Start("Notepad.exe", "MyUser", securePwd, "MYDOMAIN");
        }
        catch (Win32Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
0

Source: https://habr.com/ru/post/1773867/


All Articles