【发布时间】:2017-02-16 06:35:39
【问题描述】:
我有一个文件夹正在被FileSystemWatcher 的服务监视,我使用这个Answer 来帮助我将大文件写入其中。
但是,如果有大约(100MB 或更多)的连续文件创建,我会遇到问题。
问:我该如何解决这个问题?例如,大约 10 个文件(每个 100MB)写入我的文件夹。
注意:这个文件夹是通过我的网络访问的。可能有文件创建但没有真正完成/完成。 FileSystemWatcher 可以在不完全写入文件的情况下处理文件。
用于检查打开文件是否引发异常的当前代码
private static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open,
FileAccess.Read, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
当前代码检查是否创建了文件。
private void FSWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
var files = getFiles(FSWatcher.Path); //stores all filenames in the directory in a list
if (files.Count() > 0)
{
foreach (string file in files)
{
FileInfo file_info = new FileInfo(file);
while (IsFileLocked(file_info))
{
Thread.Sleep(5000); //Sleep if file unavailable
}
//code to process the file
}
//some code here
}
}
【问题讨论】:
标签: c# multithreading service .net-3.5 filesystemwatcher