【发布时间】:2014-12-02 05:58:09
【问题描述】:
我正在使用 C# 在 Visual Studio 中创建 Windows 服务。当我从命令行运行程序时,它按预期工作。不会抛出异常或类似的东西,并且事件日志会像平常一样写入。这是我的进入方法。
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 Folder Watcher 服务已启动然后停止。某些服务如果没有被其他服务使用,则会自动停止或程序。”根本没有任何内容写入事件日志。这是我的 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);
}
【问题讨论】:
-
Properties.Settings.Default.DestinationFolder它在本地以外的目标/正在运行的机器上寻找的文件夹路径是什么......?您确定路径甚至与您的本地环境中存在相同.. 服务在目标机器上的权利是什么..?这可能是一个权利/权限问题..?如果不是,这可能是Path问题..?另外,如果这是FileSystemWatcher服务,您为什么要调用停止..?这不应该总是运行并有一些手动干预来阻止它吗? -
CallStart 和 CallStop 仅用于从控制台运行,因为我无法直接访问 OnStart 和 OnStop 方法。所以是的,这只是应该存在的 OnStop 方法。
-
这可能是 PATH 问题是什么意思?
-
您在此处设置的本地计算机上的
File Path是什么Properties.Settings.Default.DestinationFolder并且在生产或目标计算机上是否存在相同的 FilePath .. 对于其他文件路径WatchFolder我个人会添加一些if (!Directory.Exist(this.destfolder)){then create it} -
这一切都在一台机器上。一切还在发展中。而且我无法让 OnStart 运行,所以我不确定为什么 DestinationFolder 甚至很重要。这里没有使用。但文件夹确实存在。
标签: c# windows-services