2010-08-10 6 views
3

Я пытаюсь написать небольшую службу Windows в .NET 3.5, которая проверяет каждые 10 минут или около того, если вы видите новые файлы в «C: \ demofolder», а затем отправляйте электронную почту. До сих пор я сделал это здесь, как в следующем коде, то есть ошибка в Public Sub New()Служба Windows

Imports System 
Imports System.Timers 
Imports System.ServiceProcess 
Public Class TestMyService 

    ' A timer that controls how frequenty the example writes to the 
    ' event log. 
    Private serviceTimer As Timer 

    Public Sub New() 

     ' Set the ServiceBase.ServiceName property. 
     ServiceName = "TestMyService Service" 

     ' Configure the level of control available on the service. 
     CanStop = True 
     CanPauseAndContinue = True 
     CanHandleSessionChangeEvent = True 

     ' Configure the service to log important events to the 
     ' Application event log automatically. 
     AutoLog = True 

    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. 
    End Sub 

    Protected Overrides Sub OnStop() 
     ' Add code here to perform any tear-down necessary to stop your service. 
    End Sub 

Public Shared Sub Main() 

    ' Create an instance of the TestMyService class that will write 
    ' an entry to the Application event log. Pass the object to the 
    ' shared ServiceBase.Run method. 
    ServiceBase.Run(New TestMyService) 

End Sub 


End Class 

Я получил следующее сообщение об ошибке:

Sub Main' объявляется более один раз в 'mcWinService.TestMyService': mcWinService.TestMyService.Main(), mcWinService.TestMyService.Main()

Public Shared Sub Main() 'имеет несколько определений с идентичными сигнатурами.

Открытый Sub New() 'в создаваемом конструктором типе' mcWinService.TestMyService 'должен вызывать метод InitializeComponent.

ответ

6

Попытка переместить

ServiceBase.Run (New TestMyService) от Public Shared Sub Main()

в

Protected Overrides Sub OnStart

затем удалите Public Shared Sub Main()

Кроме того, удалите Public Sub New(), поскольку вы можете установить эти свойства из «Property Windows». F7, чтобы переключиться с кода на дизайнерский вид.

Update 1: Пример службы Windows для папки мониторинга

Imports System.Net.Mail 
Imports System.Net 
Imports System.Timers 
Imports System.IO 

Public Class DemoFolderMonitor 

    Private Shared timer As System.Timers.Timer 
    Private Shared timerInterval As Integer 

    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. 

     ' Use the EventLog object automatically configured by the 
     ' ServiceBase class to write to the event log. 
     'EventLog.WriteEntry(String.Format("DemoFolderMonitor Service starting.")) 

     ' Set the Interval (1sec = 1000 milliseconds). 
     timerInterval = 2000 
     timer = New System.Timers.Timer(timerInterval) 
     EventLog.WriteEntry("DemoFolderMonitor Service starting.") 

     ' Hook up the Elapsed event for the timer. 
     AddHandler timer.Elapsed, AddressOf WatchFolder 

     timer.Interval = timerInterval 
     timer.Enabled = True 

    End Sub 

    Protected Overrides Sub OnStop() 
     ' Add code here to perform any tear-down necessary to stop your service. 
     EventLog.WriteEntry("DemoFolderMonitor Service stopping...") 

    End Sub 

    Protected Sub WatchFolder() 

     Dim watcher As New FileSystemWatcher 
     watcher.Path = "C:\Demo\" 

     watcher.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName) 

     'watch all file types. 
     watcher.Filter = "*.*" 
     ' Add event handlers. 
     AddHandler watcher.Changed, AddressOf OnChanged 
     AddHandler watcher.Created, AddressOf OnChanged 
     AddHandler watcher.Deleted, AddressOf OnChanged 
     AddHandler watcher.Renamed, AddressOf OnRenamed 

     ' Begin watching. 
     watcher.EnableRaisingEvents = True 

    End Sub 

    'Define the event handlers. 
    Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs) 
     ' Specify what is done when a file is changed, created, or deleted. 
     Dim changeLog = "File: " & e.FullPath & " " & " | Action: " & e.ChangeType.ToString 
     WriteChangeLog(changeLog) 

    End Sub 

    Private Shared Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs) 
     ' Specify what is done when a file is renamed. 
     Dim changeLog = "File" & e.OldFullPath & " " & "renamed to" & " " & e.FullPath 
     WriteChangeLog(changeLog) 

    End Sub 

    'Custom action. You can either send an e-mail or write change to local file 
    'In this example I write change to local file 
    Private Shared Sub WriteChangeLog(ByVal changeLog As String) 

     'Create a text file and write the change log to the text file 
     Dim filename As String = DateTime.Now.ToString("hh-mm-ss") & ".txt" 
     Dim writer As StreamWriter 
     writer = File.CreateText("C:\ChangeLog\" & filename) 
     writer.WriteLine("Datetime Log at {0} Log Message: {1}", DateTime.Now.ToString("MMM-dd-yyyy @ hh:mm:ss tt"), changeLog) 
     writer.Close() 

    End Sub 

End Class 

Для дальнейшей проверки соответствующего чтения:

Cheer!

+0

Спасибо за образец и ссылки. – Narazana

2

Похоже, что у вас есть другой метод Main в другом файле проекта. Сделайте проект в широком поиске слова Main и посмотрите, можете ли вы его найти.

Вы также можете исправить эту ошибку, перейдя в диалог свойств проекта и выбрав TestMyService в качестве объекта запуска, а не Sub Main.

+0

Существует общий Sub Main() в Service1.designer.vb. Я думаю, что он сгенерирован автоматически. Я выбрал TestMyService в качестве объекта запуска. Ошибка все еще есть. – Narazana

+0

@Morron: Я не понимаю, когда добавляю сервис. Если вы не написали много кода уже для этого проекта, возможно, было бы проще начать с нуля, просто создать новый сервисный проект и т. Д.В этой статье приведены шаги, которые вам необходимо предпринять: http://www.codeguru.com/vb/gen/vb_system/services/article.php/c4825 –

+0

Это совершенно новый проект. Я создал его 40 млн. Назад, чтобы научиться писать Windows Service. – Narazana