如何强制我的C#Winforms程序在任何计算机上以管理员身份运行?

如何强制我的C#Winforms程序在任何计算机上以管理员身份运行? 和任何类型的操作系统?

我需要代码解决方案(任何示例代码都会很棒)

提前致谢

您可以将此清单嵌入到您的应用程序中。

           

以下是以管理员身份运行应用程序的示例代码。

 ProcessStartInfo proc = new ProcessStartInfo(); proc.UseShellExecute = true; proc.WorkingDirectory = Environment.CurrentDirectory; proc.FileName = Application.ExecutablePath; proc.Verb = "runas"; try { Process.Start(proc); } catch { // The user refused the elevation. // Do nothing and return directly ... return; } Application.Exit(); // Quit itself 

ProcessStartInfo.Verb设置为“runas”将让它以管理员身份运行。 这是相关的FAQ

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/28f84724-af3e-4fa1-bd86-b0d1499eaefa#x_FAQAnswer91

显而易见的答案是将清单文件添加到C#项目并添加以下行:

  

但是,也可以采取一种相当不正统的方法。 我们知道注册表访问需要管理员权限。 因此,如果您有一个包含注册表写访问权限的函数,如果您不以管理员身份运行该程序,该函数将抛出System.Security.SecurityException 。 暗示您必须在程序开始时调用此函数。 如果抛出此exception,您可以通知用户以管理员身份运行该程序并关闭该程序。

 public void enforceAdminPrivilegesWorkaround() { RegistryKey rk; string registryPath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\"; try { if(Environment.Is64BitOperatingSystem) { rk = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); } else { rk = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32); } rk = rk.OpenSubKey(registryPath, true); } catch(System.Security.SecurityException ex) { MessageBox.Show("Please run as administrator"); System.Environment.Exit(1); } catch(Exception e) { MessageBox.Show(e.Message); } } 

这里,行中的true rk = rk.OpenSubKey(registryPath, true)告诉程序它需要对注册表的写访问权。

它需要Manifest文件。 只需放置清单文件并选择AsInvoker或AsAdministrator。

如果您可以访问进程,可以使用proc.Verb =“runas”;

请查看: http : //social.msdn.microsoft.com/Forums/en-US/winforms/thread/db6647a3-85ca-4dc4-b661-fbbd36bd561f