Запуск процесса от другого пользователя windows - C#
Формулировка задачи:
Всем привет. Прошу помощи в следующей ситуации. С помощью своего приложения хочу запустить процесс от имени другого пользователя следующим способом.
Какую бы учетную запись из домена я бы не использовал, кроме своей, возникает исключение о том, то неверно указан путь к папке.
Тестил данный код вне домена в рабочих домашних группах, там все работает и запускает процессы от разных пользователей. Мне кажется гадость сидит где-то в другом месте.
P.S: пробовал использовать команду RunAs в консоли, пишет попытку запуска приложения от пользователя, но приложение не запускает. В рабочей группе также все работает.
Листинг программы
- char[] pass5 = textBox2.Text.ToCharArray();
- fixed (char* c = pass5)
- {
- try
- {
- System.Security.SecureString pass = new System.Security.SecureString(c, pass5.Length);
- System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(textBox3.Text, textBox4.Text);
- psi.UserName = textBox1.Text + "@ateks.local";
- psi.Password = pass;
- psi.UseShellExecute = false;
- System.Diagnostics.Process.Start(psi);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
Решение задачи: «Запуск процесса от другого пользователя windows»
textual
Листинг программы
- class RunAs
- {
- public const UInt32 Infinite = 0xffffffff;
- public const Int32 Startf_UseStdHandles = 0x00000100;
- public const Int32 StdOutputHandle = -11;
- public const Int32 StdErrorHandle = -12;
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
- public struct StartupInfo
- {
- public int cb;
- public String reserved;
- public String desktop;
- public String title;
- public int x;
- public int y;
- public int xSize;
- public int ySize;
- public int xCountChars;
- public int yCountChars;
- public int fillAttribute;
- public int flags;
- public UInt16 showWindow;
- public UInt16 reserved2;
- public byte reserved3;
- public IntPtr stdInput;
- public IntPtr stdOutput;
- public IntPtr stdError;
- }
- internal struct ProcessInformation
- {
- public IntPtr process;
- public IntPtr thread;
- public int processId;
- public int threadId;
- }
- [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- public static extern bool CreateProcessWithLogonW(
- String userName,
- String domain,
- String password,
- LogonFlags logonFlags,
- String applicationName,
- String commandLine,
- CreationFlags creationFlags,
- UInt32 environment,
- String currentDirectory,
- ref StartupInfo startupInfo,
- out ProcessInformation processInformation);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- public static extern bool GetExitCodeProcess(IntPtr process, ref UInt32 exitCode);
- [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- public static extern UInt32 WaitForSingleObject(IntPtr handle, UInt32 milliseconds);
- [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- public static extern IntPtr GetStdHandle(IntPtr handle);
- [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- public static extern bool CloseHandle(IntPtr handle);
- [DllImport("kernel32.dll")]
- static extern uint FormatMessage(uint dwFlags, IntPtr lpSource,
- uint dwMessageId, uint dwLanguageId, [Out] StringBuilder
- lpBuffer,
- uint nSize, string[] Arguments);
- public RunAs(string proccess, string user, string password, string domain)
- {
- StartupInfo startupInfo = new StartupInfo();
- startupInfo.reserved = null;
- startupInfo.flags &= Startf_UseStdHandles;
- startupInfo.stdOutput = (IntPtr)StdOutputHandle;
- startupInfo.stdError = (IntPtr)StdErrorHandle;
- UInt32 exitCode = 0;
- ProcessInformation processInfo = new ProcessInformation();
- String currentDirectory = System.IO.Directory.GetCurrentDirectory();
- try
- {
- CreateProcessWithLogonW(
- user,
- domain,
- password,
- LogonFlags.LOGON_WITH_PROFILE,
- proccess,
- proccess,
- CreationFlags.CREATE_NEW_CONSOLE,
- (UInt32)0,
- null,
- ref startupInfo,
- out processInfo);
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- Console.WriteLine("Running ...");
- WaitForSingleObject(processInfo.process, Infinite);
- GetExitCodeProcess(processInfo.process, ref exitCode);
- Console.WriteLine(exitMessage(exitCode));
- CloseHandle(processInfo.process);
- CloseHandle(processInfo.thread);
- }
- public static string exitMessage(uint exitCode)
- {
- StringBuilder formattedMessage = new StringBuilder(100);
- uint dwChars = FormatMessage(
- 0x00001000 | 0x00002000,
- IntPtr.Zero,
- exitCode,
- 0, // Default language
- formattedMessage,
- 100,
- null);
- return formattedMessage.ToString();
- }
- }
- [Flags]
- enum CreationFlags
- {
- CREATE_SUSPENDED = 0x00000004,
- CREATE_NEW_CONSOLE = 0x00000010,
- CREATE_NEW_PROCESS_GROUP = 0x00000200,
- CREATE_UNICODE_ENVIRONMENT = 0x00000400,
- CREATE_SEPARATE_WOW_VDM = 0x00000800,
- CREATE_DEFAULT_ERROR_MODE = 0x04000000,
- }
- [Flags]
- enum LogonFlags
- {
- LOGON_WITH_PROFILE = 0x00000001,
- LOGON_NETCREDENTIALS_ONLY = 0x00000002
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д