Запуск процесса от другого пользователя windows - C#

Узнай цену своей работы

Формулировка задачи:

Всем привет. Прошу помощи в следующей ситуации. С помощью своего приложения хочу запустить процесс от имени другого пользователя следующим способом.
Листинг программы
  1. char[] pass5 = textBox2.Text.ToCharArray();
  2. fixed (char* c = pass5)
  3. {
  4. try
  5. {
  6. System.Security.SecureString pass = new System.Security.SecureString(c, pass5.Length);
  7. System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(textBox3.Text, textBox4.Text);
  8. psi.UserName = textBox1.Text + "@ateks.local";
  9. psi.Password = pass;
  10. psi.UseShellExecute = false;
  11. System.Diagnostics.Process.Start(psi);
  12. }
  13. catch (Exception ex)
  14. {
  15. MessageBox.Show(ex.Message);
  16. }
  17. }
Какую бы учетную запись из домена я бы не использовал, кроме своей, возникает исключение о том, то неверно указан путь к папке. Тестил данный код вне домена в рабочих домашних группах, там все работает и запускает процессы от разных пользователей. Мне кажется гадость сидит где-то в другом месте. P.S: пробовал использовать команду RunAs в консоли, пишет попытку запуска приложения от пользователя, но приложение не запускает. В рабочей группе также все работает.

Решение задачи: «Запуск процесса от другого пользователя windows»

textual
Листинг программы
  1.     class RunAs
  2.     {
  3.         public const UInt32 Infinite = 0xffffffff;
  4.         public const Int32 Startf_UseStdHandles = 0x00000100;
  5.         public const Int32 StdOutputHandle = -11;
  6.         public const Int32 StdErrorHandle = -12;
  7.  
  8.  
  9.         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  10.         public struct StartupInfo
  11.         {
  12.             public int cb;
  13.             public String reserved;
  14.             public String desktop;
  15.             public String title;
  16.             public int x;
  17.             public int y;
  18.             public int xSize;
  19.             public int ySize;
  20.             public int xCountChars;
  21.             public int yCountChars;
  22.             public int fillAttribute;
  23.             public int flags;
  24.             public UInt16 showWindow;
  25.             public UInt16 reserved2;
  26.             public byte reserved3;
  27.             public IntPtr stdInput;
  28.             public IntPtr stdOutput;
  29.             public IntPtr stdError;
  30.         }
  31.  
  32.         internal struct ProcessInformation
  33.         {
  34.             public IntPtr process;
  35.             public IntPtr thread;
  36.             public int processId;
  37.             public int threadId;
  38.         }
  39.  
  40.  
  41.         [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  42.         public static extern bool CreateProcessWithLogonW(
  43.              String userName,
  44.              String domain,
  45.              String password,
  46.              LogonFlags logonFlags,
  47.              String applicationName,
  48.              String commandLine,
  49.              CreationFlags creationFlags,
  50.              UInt32 environment,
  51.              String currentDirectory,
  52.              ref StartupInfo startupInfo,
  53.              out ProcessInformation processInformation);
  54.  
  55.  
  56.  
  57.  
  58.         [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  59.         public static extern bool GetExitCodeProcess(IntPtr process, ref UInt32 exitCode);
  60.  
  61.         [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  62.         public static extern UInt32 WaitForSingleObject(IntPtr handle, UInt32 milliseconds);
  63.  
  64.         [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  65.         public static extern IntPtr GetStdHandle(IntPtr handle);
  66.  
  67.         [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  68.         public static extern bool CloseHandle(IntPtr handle);
  69.  
  70.         [DllImport("kernel32.dll")]
  71.         static extern uint FormatMessage(uint dwFlags, IntPtr lpSource,
  72.         uint dwMessageId, uint dwLanguageId, [Out] StringBuilder
  73.         lpBuffer,
  74.         uint nSize, string[] Arguments);
  75.  
  76.  
  77.         public RunAs(string proccess, string user, string password, string domain)
  78.         {
  79.             StartupInfo startupInfo = new StartupInfo();
  80.             startupInfo.reserved = null;
  81.             startupInfo.flags &= Startf_UseStdHandles;
  82.             startupInfo.stdOutput = (IntPtr)StdOutputHandle;
  83.             startupInfo.stdError = (IntPtr)StdErrorHandle;
  84.  
  85.             UInt32 exitCode = 0;
  86.             ProcessInformation processInfo = new ProcessInformation();
  87.             String currentDirectory = System.IO.Directory.GetCurrentDirectory();
  88.  
  89.             try
  90.             {
  91.                 CreateProcessWithLogonW(
  92.                     user,
  93.                     domain,
  94.                     password,
  95.                     LogonFlags.LOGON_WITH_PROFILE,
  96.                     proccess,
  97.                     proccess,
  98.                     CreationFlags.CREATE_NEW_CONSOLE,
  99.                     (UInt32)0,
  100.                     null,
  101.                     ref startupInfo,
  102.                     out processInfo);
  103.             }
  104.             catch (Exception e)
  105.             {
  106.                 Console.WriteLine(e.ToString());
  107.             }
  108.  
  109.             Console.WriteLine("Running ...");
  110.             WaitForSingleObject(processInfo.process, Infinite);
  111.             GetExitCodeProcess(processInfo.process, ref exitCode);
  112.  
  113.             Console.WriteLine(exitMessage(exitCode));
  114.  
  115.             CloseHandle(processInfo.process);
  116.             CloseHandle(processInfo.thread);
  117.         }
  118.  
  119.         public static string exitMessage(uint exitCode)
  120.         {
  121.             StringBuilder formattedMessage = new StringBuilder(100);
  122.             uint dwChars = FormatMessage(
  123.             0x00001000 | 0x00002000,
  124.             IntPtr.Zero,
  125.             exitCode,
  126.             0, // Default language
  127.             formattedMessage,
  128.             100,
  129.             null);
  130.             return formattedMessage.ToString();
  131.         }
  132.  
  133.     }
  134.  
  135.     [Flags]
  136.     enum CreationFlags
  137.     {
  138.         CREATE_SUSPENDED = 0x00000004,
  139.         CREATE_NEW_CONSOLE = 0x00000010,
  140.         CREATE_NEW_PROCESS_GROUP = 0x00000200,
  141.         CREATE_UNICODE_ENVIRONMENT = 0x00000400,
  142.         CREATE_SEPARATE_WOW_VDM = 0x00000800,
  143.         CREATE_DEFAULT_ERROR_MODE = 0x04000000,
  144.     }
  145.  
  146.     [Flags]
  147.     enum LogonFlags
  148.     {
  149.         LOGON_WITH_PROFILE = 0x00000001,
  150.         LOGON_NETCREDENTIALS_ONLY = 0x00000002
  151.     }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

9   голосов , оценка 4.444 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы