c# - UAC or Userlevel 怎么克服呢!

标签 c# permissions service uac elevation

我正在尝试从用 C#(在 .net 4.0 上)编写的帮助应用程序中以编程方式重新启动服务,但是如果我通过双击运行 EXE 并右键单击并执行“以管理员身份运行”,我会遇到权限冲突有效。

但是为什么我需要这个用户是本地管理员?!

我希望应用程序正常运行,并且只在用户单击按钮重新启动服务时请求管理员权限。这能做到吗?

该解决方案需要在 xp、vista 和 windows 7 上运行。

我正在使用来自 http://www.csharp-examples.net/restart-windows-service/ 的代码

public static void RestartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    int millisec1 = Environment.TickCount;
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

    // count the rest of the timeout
    int millisec2 = Environment.TickCount;
    timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));

    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
    // ...
  }
}

最佳答案

像这样创建一个新的控制台应用程序项目:

public class RunService
{
 static int Main()(string[] args)
 {
  //TODO read serviceName and timeoutMilliseconds from args
  ServiceController service = new ServiceController(serviceName);
  try
  {
    int millisec1 = Environment.TickCount;
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

    // count the rest of the timeout
    int millisec2 = Environment.TickCount;
    timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));   service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    // TODO return status code
  }
  catch
  { 
   // ...
  }
 }
}

在你的项目中,添加对上层项目的引用,并使用类似这样的方式来调用可执行文件。不使用 runas 动词,它将提示用户提升权限。

var process = Process.Start(new ProcessStartInfo
                        {
                            Verb = "runas",
                            FileName = typeof(RunService).Assembly.Location,
                            UseShellExecute = true,
                            CreateNoWindow = true,
                        });
process.WaitForExit();
var exitCode = process.ExitCode
// TODO process exit code...

关于c# - UAC or Userlevel 怎么克服呢!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4281513/

相关文章:

ssh - 通过 cygwin openssh 执行时访问被拒绝

Android Studio 收到错误 IOException : Operation not permitted while creating file

javascript - 如何在 Angular 2 中创建单例服务并读取 URL 参数

java - 如何从 Tomcat 8 中的 `HttpServletRequest` 获取服务

c# - 从休眠中唤醒时的通知 C#

c# - 成员隐藏,其实际用途是什么

c# - 将查询字符串传递给 mvc View 操作

c# - 是否有将 T-SQL 存储过程转换为 C# 的工具?

mysql - 用户 'user' @'localhost' 的访问被拒绝(使用密码 : YES) in Apache Nifi

android - 如何使用 Hilt 将 SharedPreferences 注入(inject)后台服务