Windows服务无法解释地停止在SCM中启动
问题描述:
我正在使用C#在Visual Studio中制作Windows服务。当我从命令行运行程序时,它按预期工作。没有例外被抛出或类似的东西,并且事件日志get被写入正常。这是我的入门方法。Windows服务无法解释地停止在SCM中启动
var service = new CSFolderWatcher();
if (Environment.UserInteractive)
{
service.CallStart(args);
Console.WriteLine("Press enter to stop program");
Console.Read();
service.CallStop();
}
else
{
ServiceBase.Run(new ServiceBase[] { new CSFolderWatcher() });
}
然而,当我进入SCM启动该服务,一箱立即弹出,上面写着“本地计算机上的CS文件夹看守服务启动后又停止了,一些服务自动停止,如果他们不由其他服务或程序使用。“根本没有任何东西写到事件日志中。这是我在onStart代码:
internal void CallStart(string[] args) { OnStart(args); }
internal void CallStop() { OnStop(); }
protected override void OnStart(string[] args)
{
this.ServiceName = MyServiceName;
Properties.Settings.Default.Reload();
this.destfolder = Properties.Settings.Default.DestinationFolder;
this.watchfolder = Properties.Settings.Default.WatchFolder;
this.watchfilter = Properties.Settings.Default.WatchFilter;
LogEvent(this.ServiceName + " starting" + "\r\n" +
"Destination folder: " + this.destfolder + "\r\n" +
"Watch Folder: " + this.watchfolder + "\r\n" +
"Watch Filter: " + this.watchfilter + "\r\n" +
"OnStart args: " + string.Join(", ", args));
// Create a new FileSystemWatcher with the path
//and text file filter
try { watcher = new FileSystemWatcher(watchfolder, watchfilter); }
catch (Exception e) { LogEvent(e.ToString()); throw; }
watcher.IncludeSubdirectories = Properties.Settings.Default.WatchSubdirectories;
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.EnableRaisingEvents = true;
}
下面是的LogEvent代码:
private void LogEvent(string message)
{
string eventSource = MyServiceName;
DateTime dt = new DateTime();
dt = System.DateTime.UtcNow;
message = dt.ToLocalTime() + ": " + message;
Console.WriteLine(message);
EventLog.WriteEntry(eventSource, message);
}
答
的问题原来是你不能从OnStart方法设置ServiceName属性。 this.ServiceName = MyServiceName;
应该在构造函数中,因为它似乎是是设置它所必需的。
ServiceName标识服务到服务控制管理器。此属性的值必须与相应安装程序类的ServiceInstaller.ServiceName属性中记录的服务名称相同。在代码中,服务的ServiceName通常在可执行文件的main()函数中设置。
'Properties.Settings.Default.DestinationFolder'是什么在寻找目标/跑步机本地以外的文件夹路径..?你确定这些路径的存在与你的本地环境相同吗?服务在目标机器上有什么权利..?这可能是一个权利/权限问题..?如果不是这可能是一个'路径问题..??如果这是一个'FileSystemWatcher'服务,你为什么叫停止..?不应该总是运行,并有一些手动干预来阻止它..? – MethodMan 2014-12-01 20:16:25
CallStart和CallStop仅用于从控制台运行,因为我无法直接访问OnStart和OnStop方法。所以是的,这只是应该在那里的OnStop方法。 – 2014-12-01 20:24:58
你是什么意思,它可能是一个PATH问题? – 2014-12-01 20:26:47