【问题标题】:How to make FileSystemWatcher trigger action after files are created and closed?创建和关闭文件后如何使 FileSystemWatcher 触发操作?
【发布时间】:2014-05-20 21:06:53
【问题描述】:

我使用下面的代码来启动

$folder = '....' 
$filter = '*.csv' 
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
    IncludeSubdirectories = $true;
    NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite' }
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
    ... #execute a program to read the files, 
    ... #may fail because file is still being writing..... }

但是,我会在创建文件后立即触发该操作。文件夹中可能有数百个拥抱文件要转储/复制。是否可以测试文件写入是否完成?

【问题讨论】:

    标签: c# windows powershell filesystemwatcher


    【解决方案1】:

    一种可能性:

    Try {
      [IO.File]::OpenWrite($File).Close()
      #Do something with file
    }
    Catch {}
    

    如果文件已完成写入并已关闭,[IO.File]::OpenWrite($File).Close() 将打开文件进行写入,然后立即关闭它。如果仍在写入,则无法获得写入锁,命令将失败,脚本将进入 Catch 块并等待下一个 LastWrite 事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多