我有這種情況的一個問題: 我做了2個節目:C#程序如何以管理員權限運行另一個程序?
第一個只是打印輸出稱與管理provileges推出與否,和第二個,執行第一條程序擁有管理員權限且不使用UAC。麻煩的是,第二個程序無法啓動具有管理員權限的第一個程序,我不知道爲什麼。 這是我的代碼:
的第一個程序的代碼:
// This only prints if you start as administrator or not.
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
Console.WriteLine("I got admin privileges?: "+isElevated);
代碼的第二方案:
// This execute the first program with admin privileges without UAC
string username = "myuser";
SecureString userpass = new SecureString();
userpass.AppendChar('m');
userpass.AppendChar('y');
userpass.AppendChar('p');
userpass.AppendChar('a');
userpass.AppendChar('s');
userpass.AppendChar('s');
Process program = new Process();
program.StartInfo.UserName = username;
program.StartInfo.Password = userpass;
program.StartInfo.FileName = "Path/First_program.exe";
program.StartInfo.UseShellExecute = false;
program.Start();
PD:我不希望用戶打開UAC,這就是爲什麼我已經插入用戶名和密碼。 在此先感謝。
據我所知,你不能以這種方式繞開UAC。如果正在運行的程序沒有管理權限,則被調用的程序需要請求將觸發UAC的管理權限。 – itsme86
你有沒有嘗試使密碼'SecureString'只讀? –
@ BenVoigt,「SecureString」工作正常,因爲當我寫一個錯誤的密碼它會引發一個異常。 – suffuko