我有一个文件夹被FileSystemWatcher
服务监视,我用这个Answer来帮助我写入大文件。如何处理由FileSystemWatcher监视的文件夹中的快速连续文件创建?
但是,如果有连续的文件创建(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
}
}