这是我第一次使用文件监视器编写Windows服务。这正是我想要完成的。:
问题:
问题: 这是它假设工作的方式。服务开始后,只需提高一次?如果是,我需要做什么才能让服务继续观看文件?
非常感谢任何帮助。提前致谢 !
我的代码在
下面MyNewService.vb
Imports System.IO
Public Class MyNewService
Public Sub New()
MyBase.New()
' This call is required by the designer.
InitializeComponent()
If Not System.Diagnostics.EventLog.SourceExists("MySource") Then
System.Diagnostics.EventLog.CreateEventSource("MySource",
"MyNewLog")
End If
EventLog1.Source = "MySource"
EventLog1.Log = "MyNewLog"
End Sub
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
EventLog1.WriteEntry("In OnStart")
Dim watcher As New FileSystemWatcher
With watcher
.Filter = "test.txt*" 'To chatch only txt files
.IncludeSubdirectories = True
.NotifyFilter = NotifyFilters.LastWrite
.Path = "C:\Users\uname\Desktop\FSW Test\"
End With
'Add event handlers
AddHandler watcher.Changed, AddressOf OnChanged
AddHandler watcher.Created, AddressOf OnChanged
AddHandler watcher.Deleted, AddressOf OnChanged
AddHandler watcher.Renamed, AddressOf OnRenamed ' not implemented. Leaving them for future use
'Begin watching
watcher.EnableRaisingEvents = True
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
EventLog1.WriteEntry("In OnStop.")
End Sub
Protected Overrides Sub OnContinue()
EventLog1.WriteEntry("In OnContinue.")
End Sub
Dim lastRead As DateTime = DateTime.MinValue
Private Sub OnChanged(sender As Object, e As FileSystemEventArgs)
Dim lastWriteTime As DateTime = File.GetLastAccessTime("C:\Users\uname\Desktop\FSW Test\test.txt")
If lastWriteTime <> lastRead Then ' Use to skype one of the times this event is raised
'Opens pogram 'WindowsApplication2.exe' and passes parameters
RunApp()
lastRead = lastWriteTime
End If
End Sub
Private Sub OnRenamed(sender As Object, e As RenamedEventArgs)
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath)
End Sub
Public Sub RunApp()
Dim test As String = TimeOfDay.ToString("h:mm:ss")
Dim pHelp As New ProcessStartInfo
With pHelp
.FileName = "C:\Users\uname\Documents\Visual Studio 2010\Projects\Substation\TriggerMF\WindowsApplication2\bin\Debug\WindowsApplication2.exe"
.Arguments = test
.CreateNoWindow = True
'.UseShellExecute = True
.WindowStyle = ProcessWindowStyle.Hidden
End With
Process.Start(pHelp)
End Sub
结束班