gpt4 book ai didi

c# - 带有 FileSystemWatcher 的目录扫描器 Windows 服务

转载 作者:太空宇宙 更新时间:2023-11-03 11:37:09 25 4
gpt4 key购买 nike

我正在尝试创建一个 Windows 服务,它将抓取上传到目录的新文件,编辑它们并移动到其他目录。看来我可以复制它们但不能移动。这是为什么?

using System;
using System.ServiceProcess;
using System.Threading;
using System.IO;

namespace ImportService
{
public class ImportServer : ServiceBase
{
private System.Diagnostics.EventLog eventLog1;
private FileSystemWatcher watcher;

public ImportServer()
{
this.ServiceName = "ImportService";

this.CanHandlePowerEvent = true;
this.CanHandleSessionChangeEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
this.AutoLog = true;

InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("ImportServiceLogSource"))
System.Diagnostics.EventLog.CreateEventSource("ImportServiceLogSource", "ImportServiceLog");
eventLog1.Source = "ImportServiceLogSource";
eventLog1.Log = "ImportServiceLog";
}

public static void Main()
{
ServiceBase.Run(new ImportServer());
}

protected override void OnStart(string[] args)
{
//base.OnStart(args);

eventLog1.WriteEntry("service started");

watcher = new FileSystemWatcher();
watcher.Path = "C:\\INPUT\\";
watcher.Filter = "*.jpg";
watcher.EnableRaisingEvents = true;
watcher.Created += new FileSystemEventHandler(OnCreated);
}

private void OnCreated(object sender, FileSystemEventArgs e)
{
String output_dir = "C:\\OUTPUT\\";
String output_file = Path.Combine(output_dir, e.Name);
File.Move(e.FullPath, output_file);
// File.Copy() works here
eventLog1.WriteEntry("moving file to " + output_file);
}

protected override void OnStop()
{
eventLog1.WriteEntry("service stopped");
base.OnStop();
}

protected override void OnContinue()
{
base.OnContinue();
}

protected override void OnPause()
{
base.OnPause();
}

private void InitializeComponent()
{
this.eventLog1 = new System.Diagnostics.EventLog();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();

}
}
}

我还应该保留 base.OnStart(); 等。它到底做了什么?

更新:如何移动在监视目录中创建的文件? File already in use异常问题。

最佳答案

您必须捕获 IOException 并让线程休眠一段时间,然后重试。

private void OnCreated(object sender, FileSystemEventArgs e)
{
String output_dir = "C:\\OUTPUT\\";
String output_file = Path.Combine(output_dir, e.Name);
while (true)
{
try
{
File.Move(e.FullPath, output_file);
break;
}
catch (IOException)
{
//sleep for 100 ms
System.Threading.Thread.Sleep(100);
}
}
eventLog1.WriteEntry("moving file to " + output_file);
}

话虽这么说,但这有很多问题。你最好拥有一个每隔几秒调用一次的计时器事件来查找文件夹中的文件。如果您得到一个 IOException,您就可以继续了。该文件仍将在那里进行下一次迭代处理(假设上传已完成)。如果需要,可以举个例子说明我在说什么。

关于c# - 带有 FileSystemWatcher 的目录扫描器 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5896109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com