我正在尝试从用 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/