我回答了我的发现,因为它可能对他人有用。我声称没有原创性,因为所有代码都来自其他代码。我选择创建一个单独的可执行文件来运行文件关联设置。我从一个菜单项调用该程序:
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