您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将多个文件添加到目录中时,FileSystemWatcher的文件访问错误

将多个文件添加到目录中时,FileSystemWatcher的文件访问错误

这种方法的典型问题是在触发事件时仍在复制文件。显然,您会得到一个例外,因为文件在复制过程中被锁定。大文件特别有可能发生异常。

解决方法是,您可以先复制文件,然后重命名文件并侦听重命名事件。

或者另一个选择是进行while循环,以检查是否可以使用写访问权限打开文件。如果可以,您将知道复制已完成。C#代码可能看起来像这样(在生产系统中,您可能希望具有最大的重试次数或超时次数,而不是while(true)):

/// <summary>
/// Waits until a file can be opened with write permission
/// </summary>
public static void WaitReady(string fileName)
{
    while (true)
    {
        try
        {
            using (Stream stream = System.IO.File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                if (stream != null)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} ready.", fileName));
                    break;
                }
            }
        }
        catch (FileNotFoundException ex)
        {
            System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", fileName, ex.Message));
        }
        catch (IOException ex)
        {
            System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", fileName, ex.Message));
        }
        catch (UnauthorizedAccessException ex)
        {
            System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", fileName, ex.Message));
        }
        Thread.Sleep(500);
    }
}

另一种方法是在复制完成后在文件夹中放置一个小的触发器文件。您的FileSystemWatcher将仅侦听触发器文件

其他 2022/1/1 18:17:46 有500人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶