创建一个vb.net Windows服务,每隔1小时从服务器下载新上传的文件

时间:2017-01-19 07:06:49

标签: vb.net windows service

我需要帮助创建一个vb.net Windows服务,每1分钟从服务器下载新上传的文件到本地计算机。一旦服务启动,此代码下载相同的文件,但计时器在此处不起作用。

我想服务检测上传到服务器上的新文件并下载它,并且计时器应该在每分钟后定期检查新文件。以下是我的代码。请帮助我。

Imports System    
Imports System.IO    
Imports System.Threading    
Imports System.Net    
Imports System.Threading.Timer

Public Class Service1

    Dim MyThread As Threading.Thread
    Protected Overrides Sub OnStart(ByVal args() As String)
        Try
            Timer2.Enabled = True
            MyThread = New Threading.Thread(AddressOf FTPDownloadFile)
            MyThread.Start()
            AddHandler Timer2.Tick, AddressOf Timer2_Tick
            Timer2.Interval = 60000 ' 1 minute time interval
            Timer2.Start()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub    

 Protected Overrides Sub OnStop()

        ' Add code here to perform any tear-down necessary to stop your service.

        Timer2.Enabled = False
        MyThread.Abort()

    End Sub

    Private Sub FTPDownloadFile()
        Dim ftpuri As String = ""
        Dim downloadpath As String = ""
        Dim ftpusername As String = ""
        Dim ftppassword As String = ""

        'Create a WebClient.
        Dim request As New WebClient()

        ' Confirm the Network credentials based on the user name and password passed in.
        request.Credentials = New NetworkCredential("abc", "1234")

        'Read the file data into a Byte array
        Dim bytes() As Byte = request.DownloadData("http://iba-iet.netai.net/wordpress/home-2")



        Try
            '  Create a FileStream to read the file into
            Dim DownloadStream As FileStream = IO.File.Create("C:\file.html")
            '  Stream this data into the file
            DownloadStream.Write(bytes, 0, bytes.Length)
            '  Close the FileStream
            DownloadStream.Close()

        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try

        MsgBox("Process Complete")

    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        Try
            FTPDownloadFile()
            Timer2.Stop()
        Catch ex As Exception
        Finally
            Timer2.Start()
        End Try
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

Imports System
Imports System.IO
Imports System.Net
Imports System.Timers
Imports System.Threading

Public Class Service1
Dim _oTimer As New System.Timers.Timer()
Dim _shutdownEvent As New ManualResetEvent(False)
Dim _processEvent As New ManualResetEvent(False)
Dim _thread As Thread
Protected Overrides Sub OnStart(ByVal args() As String)

    'Setting Thread and Timmer to Pool for jobs
    _thread = New Thread(AddressOf Execute)
    _thread.IsBackground = False
    _thread.Start()
    AddHandler _oTimer.Elapsed, Function(sender, e) _processEvent.[Set]()
    _oTimer.AutoReset = False
    _oTimer.Interval = 10000
    _oTimer.Enabled = True

End Sub

Protected Overrides Sub OnStop()
    _shutdownEvent.[Set]()
    _thread.Join()
    _oTimer.[Stop]()
    _oTimer.Dispose()
End Sub

Private Sub Execute()
    Dim [handles] = New WaitHandle() {_shutdownEvent, _processEvent}
    Try
        While Not _shutdownEvent.WaitOne(0)
            Select Case WaitHandle.WaitAny([handles])
                Case 0 ' Shutdown Event
                    Exit Select
                Case 1
                    FTPDownloadFile()
                    _processEvent.Reset() ' reset for next time
                    _oTimer.Start() ' trigger timer again
                    Exit Select
            End Select
        End While
    Catch ex As Exception
    End Try
End Sub

Private Sub FTPDownloadFile()
    Dim FTPUri As String = "ftp://mywebsite.com/"
    Dim FTPUser As String = "abc"
    Dim FTPPwd As String = "123"
    Dim LocalPath As String = "C:\Myfolder\"

    Dim request As FtpWebRequest = DirectCast(WebRequest.Create(FTPUri), FtpWebRequest)
    request.Method = WebRequestMethods.Ftp.ListDirectory
    request.Credentials = New NetworkCredential(FTPUser, FTPPwd)
    Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
    Dim responseStream As Stream = response.GetResponseStream()
    Dim reader As New StreamReader(responseStream)
    Dim ListDirectory As New List(Of String)()
    Dim line As String = reader.ReadLine()

    While Not String.IsNullOrEmpty(line)
        ListDirectory.Add(line)
        line = reader.ReadLine()
    End While

    reader.Close()
    response.Close()

    Using WebClient As New WebClient()
        WebClient.Credentials = New System.Net.NetworkCredential(FTPUser, FTPPwd)
        For i As Integer = 0 To ListDirectory.Count - 1
            Dim LocalFilePath = LocalPath & ListDirectory(i).ToString()
            If ListDirectory(i).Contains(".") AndAlso Not File.Exists(LocalFilePath) Then
                Dim FTPPath As String = FTPUri & ListDirectory(i).ToString()
                WebClient.DownloadFile(FTPPath, LocalFilePath)
            End If
        Next
    End Using
End Sub
End Class