VB.NET FileSystemWatcher - 复制创建的文件

时间:2014-01-13 11:37:44

标签: vb.net filesystemwatcher

^^^答案是在C#中!我正在使用VB.NET! ^^^

我正在使用FileSystemWatcher监视新文件的文件夹。

当检测到更改时会触发此子程序,然后将该文件复制到服务器。

   Private Sub OnCreated(source As Object, e As FileSystemEventArgs)
        Dim LocalFile As String = e.FullPath
        Dim ServerFile As String = LocalFile.Replace(localSyncPath, serverSyncPath)

        Try
            File.Copy(LocalFile, ServerFile)
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try

    End Sub

问题是,这通常会弹出一个错误,说该文件正在使用中。有没有办法运行循环继续尝试,直到它工作?或者甚至复制正在使用的信息?

1 个答案:

答案 0 :(得分:1)

我给你检查的link很容易翻译成VB.NET:

Public Shared Sub listener_Created(sender As Object, e As FileSystemEventArgs)
    Console.WriteLine("File Created:" & vbLf + "ChangeType: " + e.ChangeType + vbLf & "Name: " + e.Name + vbLf & "FullPath: " + e.FullPath)
    Try
        File.Copy(e.FullPath, "D:\levani\FolderListenerTest\CopiedFilesFolder\" + e.Name)
    Catch
        _waitingForClose.Add(e.FullPath)
    End Try
    Console.Read()
End Sub

Public Shared Sub listener_Changed(sender As Object, e As FileSystemEventArgs)
    If _waitingForClose.Contains(e.FullPath) Then
        Try
            File.Copy(...)
            _waitingForClose.Remove(e.FullPath)
        Catch
        End Try
    End If
End Sub