如何强制我的项目在Visual Studio 2013中始终以管理员身份运行?

Cam*_*Dev 5 c# wpf service elevated-privileges visual-studio-2013

我在Visual Studio 2013中有一个WPF项目,这个项目有两个按钮.第一个按钮表示启动服务,第二个按钮表示停止服务.当我以管理员身份运行Visual Studio时,按钮可以正常工作.但是当我打开没有特权的Visual Studio时,会出现InvalidOperationException异常.

当Visual Studio不以管理员身份运行时,如何强制我的项目从特权开始?

我将app.manifest添加到我的项目中并进行了更改

level ="requireAdministrator"uiAccess ="false"/>

但它没有起作用.

为了启动或停止我的服务,我使用的是ServiceController.

Meh*_*rad 7

正如Torben M. Philippsen在他的文章中提到的那样:

  • 在Visual Studio 2010中(我猜这同样适用于VS2008,但我还没有测试过它)右键单击您的项目并选择"添加新项目"
  • 添加应用程序清单文件 - 默认名称为app.manifest.
  • 在清单文件中,从中更改现有配置

    <requestedExecutionLevel level="asInvoker" uiAccess="false" />
    
    Run Code Online (Sandbox Code Playgroud)

    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
    
    Run Code Online (Sandbox Code Playgroud)
  • 保存并关闭清单文件.

  • 请注意,您的清单文件不会显示在解决方案的任何位置.要解决此问题,请在解决方案资源管理器中单击"显示所有文件"按钮.
  • 重要说明:右键单击清单文件并将其添加到项目中 - 我们需要这样做以告诉VS在编译应用程序时使用清单文件.
  • 右键单击您的项目,然后选择"属性".
  • 在应用程序选项卡的底部,选择清单文件:

选择清单文件

清单文件选择

  • 编译并运行应用程序.如果启用了您的UAC设置,系统将提示您允许应用程序以提升模式启动.

  • 有时它可以派上用场检查您的应用程序是否实际上是在高架模式下运行.也许你会发现这个codesnippet有用:

     WindowsPrincipal myPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
     if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator) == false )
     {
         //show messagebox - displaying a messange to the user that rights are missing
         MessageBox.Show("You need to run the application using the \"run as administrator\" option", "administrator right required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     }
     else
     {
         MessageBox.Show("You are good to go - application running in elevated mode", "Good job" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
    
    Run Code Online (Sandbox Code Playgroud)


小智 2

这很有趣,似乎您需要更改项目运行方式的权限,请尝试执行以下操作

  • 转到项目属性 > 安全性
  • 启用单击一次安全设置并选择完全信任应用程序

有关更多信息,请参阅此链接 WPF 安全性