Windows服务监视c#中的文件下载目录
本文关键字:文件下载 服务 监视 Windows | 更新日期: 2023-09-27 18:04:21
我对Windows世界相当陌生,因为我的大部分主要开发都是使用UNIX系统。一位客户提出了一个特别的要求,问我是否可以编写一个windows服务来监视下载文件夹中的任何下载内容,并将其移动到他们的文档文件夹中。出于某种原因,他们不想更改浏览器上的默认下载目录。
所以为了满足顾客的要求,我想我应该试一试。下面是我的尝试:
protected override void OnStart(string[] args)
{
watch();
}
public void OnDebug()
{
OnStart(null);
}
protected override void OnStop()
{
}
String path = null;
private void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
path = Path.Combine(pathUser, "Downloads");
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
String pUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
String directoryName = Path.Combine(pUser, "Documents"); ;
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if (dirInfo.Exists == false)
Directory.CreateDirectory(directoryName);
List<String> MyFiles = Directory
.GetFiles(path, "*.*", SearchOption.AllDirectories).ToList();
foreach (string file in MyFiles)
{
FileInfo mFile = new FileInfo(file);
// to remove name collusion
if (new FileInfo(dirInfo + "''" + mFile.Name).Exists == false)
mFile.MoveTo(dirInfo + "''" + mFile.Name);
}
}
我在调试模式下测试了我的代码,当服务运行时,我去下载文件,下载失败。然后Visual Studio弹出如下错误:
"An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file because it is being used by another process."
错误被抛出:
mFile.MoveTo(dirInfo + "''" + mFile.Name);
我该如何解决这个问题?
下载开始,在下载文件夹中创建一个临时文件,该文件开始接收下载流。但是,一旦创建了临时文件,您的移动应用程序就会尝试拦截并移动显然被另一个进程锁定的文件,因为下载客户端仍在写入该文件。也许您可以在下载文件夹中缓存一个文件列表以及文件大小,并在移动之前检查它以确保大小没有改变。您还可以排除与下载相关的已知扩展。如。*。临时,* .downloading由于您正在处理一个动态文件系统,其中用户可以随时锁定文件,因此您可能还希望更优雅地处理被锁定的文件异常。