1

这是我第一次制作 Windows 服务应用程序。我正在尝试使用 Windows 服务应用程序将文件从一个文件夹移动到另一个文件夹。它会每 10 秒执行一次。这是我正在使用的代码。当我在 Windows 窗体应用程序上使用它时它可以工作,但当我在 Windows 服务应用程序上使用它时它不起作用。

如果我在 OnStart 中使用 Timer1_Tick 中的代码,它就可以工作。但在计时器中不起作用。

    Protected Overrides Sub OnStart(ByVal args() As String)
        Timer1.Enabled = True
    End Sub

    Protected Overrides Sub OnStop()
        Timer1.Enabled = False
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim FileToMove As String
        Dim MoveLocation As String
        Dim count1 As Integer = 0
        Dim files() As String = Directory.GetFiles("C:\Documents and Settings\dmmc.operation\Desktop\Q8")
        Dim pdfFiles(100) As String

        For i = 0 To files.Length - 1
            If Path.GetExtension(files(i)) = ".pdf" Then
                pdfFiles(count1) = files(i)
                count1 += 1
            End If
        Next

        For i = 0 To pdfFiles.Length - 1
            If pdfFiles(i) <> "" Then
                FileToMove = pdfFiles(i)
                MoveLocation = "C:\Documents and Settings\dmmc.operation\Desktop\Output\" + Path.GetFileName(pdfFiles(i))
                If File.Exists(FileToMove) = True Then
                    File.Move(FileToMove, MoveLocation)
                End If
            End If
        Next

    End Sub
4

2 回答 2

1

如果没有实例化 Form,Windows.Forms.Timer 将无法工作。您应该改用 System.Timers.Timer :

Private WithEvents m_timer As System.Timers.Timer

Protected Overrides Sub OnStart(ByVal args() As String)
    m_timer = New System.Timers.Timer(1000)   ' 1 second
    m_timer.Enabled = True
End Sub

Private Sub m_timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles m_timer.Elapsed
    m_timer.Enabled = False

    'Do your stuff here

    m_timer.Enabled = True
End Sub
于 2012-11-11T06:59:44.337 回答
0

我还构建了一项服务,该服务可以移动放入文件夹中的文件,但我使用的是 FileSystemWatcher。FileSystemWatcher 允许我在创建新文件时移动文件,在 SQL 数据库中创建条目并在完成后发送电子邮件通知。

这就是我设置 FileSystemWatcher 的方式

  1. 设置要观看的文件夹:watcher.Path = "C:\Folder to Watch"
  2. 设置要观看的文件类型:watcher.Filter = "*.pdf"。
  3. 要监视的事件类型和触发的方法:watcher.Created += new FileSystemEventHandler(OnChanged);
  4. 最后,我需要启用事件: watcher.EnableRaisingEvents = true;

不幸的是,我每天都有文件无法成功移动的情况。我得到正在使用的文件的 IO 异常。文件被复制,但目标文件夹中的文件为 0kb。

我正在尝试对其进行故障排除,并且我已经设法远程调试,但我仍然没有弄清楚我做错了什么。

我得到的最常见错误是:错误:System.IO.IOException:该进程无法访问文件“fileName.pdf”,因为它正在被另一个进程使用。

此错误没有意义,因为在我的服务尝试移动它之前该文件不存在...

任何进一步的帮助将不胜感激。

于 2019-02-21T19:38:41.773 回答