Launch a process under another user's credentials

后端 未结 3 1100
一向
一向 2020-11-29 09:39

I want to launch a process under another username\'s credentials. This is what I have now:

        /// 
        /// Do actions under another          


        
3条回答
  •  野性不改
    2020-11-29 10:28

    It might be weird for some people, my apologies, I am Linux developer... Tested:

        /// 
        /// Class that deals with another username credentials
        /// 
        class Credentials
        {
            /// 
            /// Constructor of SecureString password, to be used by RunAs
            /// 
            /// Plain password
            /// SecureString password
            private static SecureString MakeSecureString(string text)
            {
                SecureString secure = new SecureString();
                foreach (char c in text)
                {
                    secure.AppendChar(c);
                }
    
                return secure;
            }
    
            /// 
            /// Run an application under another user credentials.
            /// Working directory set to C:\Windows\System32
            /// 
            /// Full path to the executable file
            /// Username of desired credentials
            /// Password of desired credentials
            public static void RunAs(string path, string username, string password)
            {
                try
                {
                    ProcessStartInfo myProcess = new ProcessStartInfo(path);
                    myProcess.UserName = username;
                    myProcess.Password = MakeSecureString(password);
                    myProcess.WorkingDirectory = @"C:\Windows\System32";
                    myProcess.UseShellExecute = false;
                    Process.Start(myProcess);
                }
                catch (Win32Exception w32E)
                {
                    // The process didn't start.
                    Console.WriteLine(w32E);
                }
            }
    
        }
    

提交回复
热议问题