【发布时间】:2017-11-16 13:05:15
【问题描述】:
我正在编写一个 FileSystemWatcher,每当图像上传到文件夹 A 时,它将图像从文件夹 A 复制到文件夹 B。我试图将其用作服务器 PC 上的 Windows 服务,但我有我的文件在复制时被锁定的一些问题。我想我已经找到了问题的根源,但我没有任何运气解决它。因此,当我运行我的 Windows 服务时,它总是在第一张或第二张图片上传时意外结束。我收到的错误消息是这样的:The process cannot access the file 'filepath' because it is being used by another process.
我的代码的相关部分:
public void WatchForChanges()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Program.SourceFolder;
watcher.Created += new FileSystemEventHandler(OnImageAdded);
watcher.EnableRaisingEvents = true;
watcher.IncludeSubdirectories = true;
}
public void OnImageAdded(object source, FileSystemEventArgs e)
{
FileInfo file = new FileInfo(e.FullPath);
ImageHandler handler = new ImageHandler();
if (handler.IsImage(file))
{
handler.CopyImage(file);
}
}
还有我的 CopyImage 方法,其中包括我针对此问题提出的解决方案之一,它利用了一个 while 循环来捕获错误并重试图像的复制:
public void CopyImage(FileSystemInfo file)
{
// code that sets folder paths
// code that sets folder paths
bool retry = true;
if (!Directory.Exists(targetFolderPath))
{
Directory.CreateDirectory(targetFolderPath);
}
while (retry)
{
try
{
File.Copy(file.FullName, targetPath, true);
retry = false;
}
catch (Exception e)
{
Thread.Sleep(2000);
}
}
}
但是这个CopyImage 解决方案只是继续复制同一个文件,这对我来说不是很理想。我希望这已经足够了,但遗憾的是,我有一排图像在等待。
【问题讨论】:
-
而不是使用
while (retry)将失败的副本写入HashSet<string>。定期循环HashSet并重试。 -
相关文件可能仍在写入过程中。也许您应该使用队列,类似于@mjwills 的建议。
标签: c# filesystemwatcher