我有以下简单的服务程序:
using System.Diagnostics;
using System.ServiceProcess;
namespace BasicService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
Verb = "runas",
UserName = "jdoe",
Password = "XXXXXXX".ConvertToSecureString(),
Domain = "abc.com",
UseShellExecute =false,
FileName = "notepad.exe"
};
Process.Start(processStartInfo);
}
protected override void OnStop()
{
}
}
}
我将其用作我的服务安装程序:
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace BasicService
{
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private readonly ServiceProcessInstaller _process;
private readonly ServiceInstaller _service;
public ProjectInstaller()
{
_process = new ServiceProcessInstaller {Account = ServiceAccount.LocalSystem};
_service = new ServiceInstaller
{
ServiceName = "BasicService",
Description = "Just a testing service.",
StartType = ServiceStartMode.Automatic,
};
Installers.Add(_process);
Installers.Add(_service);
}
}
}
如果我在没有指定动词、用户名、密码、域和 useshellexecute 的情况下运行此服务,一切都运行得很好。如上所示,一旦我指定了这些值,我就会得到以下信息:
Service cannot be started. System.ComponentModel.Win32Exception (0x80004005): Access is denied at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) at System.Diagnostics.Process.Start() at System.Diagnostics.Process.Start(ProcessStartInfo startInfo) at BasicService.Service1.OnStart(String[] args) in C:\BasicService\BasicService\Service1.cs:line 24 at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
有什么想法吗?
最佳答案
从 Windows Vista 开始,服务不能简单地显示 ui 或与用户交互。
http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx
因此,要从您的服务运行 GUI 应用程序,您需要使用 CreateProcessAsUser,这在 .NET 中不直接可用。因此,您将不得不依赖 Pinvoke,它与此处描述的有些相似
关于c# - 如何使用 'local system' 服务以域用户身份运行单独的进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9133105/