我回答了我的發現,因爲它可能對他人有用。我聲稱沒有原創性,因爲所有代碼都來自其他代碼。我選擇創建一個單獨的可執行文件來運行文件關聯設置。我從一個菜單項調用該程序:
var proc = new ProcessStartInfo {
UseShellExecute = true,
WorkingDirectory = Environment.CurrentDirectory,
FileName = Path.Combine(Application.StartupPath, "ADEFileAssociator.exe"),
Verb = "runas"
};
try {
Process.Start(proc);
}
catch {
MessageBox.Show("Failed to start File Associator","Process Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
}
此方法在另一個問題的答案中描述,並且正常工作。文件關聯器應用程序雙重檢查用戶使用的操作系統,如果操作系統爲Vista或更高版本,並且該應用程序未以管理員權限啓動,則無法啓動。我這樣做是因爲用戶可以直接運行外部應用程序。我使用的代碼是這樣的:
var safeToRun = true;
var os = Environment.OSVersion;
if (os.Version.Major > 5) {//Got Vista or Win7
if (!IsElevated) {
var message = new StringBuilder();
message.AppendLine("You are running Vista or Win7 and this program ");
message.AppendLine("needs to run with Admin Privileges. When the ");
message.AppendLine("program closes please right click on the executable");
message.AppendLine("or icon and select 'Run As Administrator'.");
message.AppendLine("");
message.AppendLine("The Program will now close.");
MessageBox.Show(message.ToString(), "Insufficient Privileges", MessageBoxButtons.OK, MessageBoxIcon.Error);
safeToRun = false;
}
}
if (safeToRun) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
IsElevated檢查當前權限的:
public static bool IsElevated {
get {
return new WindowsPrincipal
(WindowsIdentity.GetCurrent()).IsInRole
(WindowsBuiltInRole.Administrator);
}
}
再次,這是不是我的代碼,而是從另一個答案。
雖然我確定有人會有更好的方式來做到這一點。我的外部應用程序是WinForm,雖然它可能是一個命令行。
編輯 遵循David的評論和建議我知道這不是一個很好的做事方式。不過,我希望整體問題和答案(特別是David的意見)對其他人有指導意義
你知道每個用戶的關聯,不需要提升權限設置? – 2011-05-07 07:42:20
不,我不知道那 – ScruffyDuck 2011-05-07 07:44:48
查看它的網絡。看起來好於在外部安裝時間提高 – 2011-05-07 07:46:20