We're working hard on the next version of Developer Fusion. Let us know what you think
we should be up to!
Members
Technology Zones
Articles
Hosted By
Info
|
[3636] Watching Folder Activity in VB.NET
Last post 02-06-2008 12:28 AM by D'Scouser. 14 replies.
-
01-01-1999 12:00 AM
|
|
-
-
-
-
-
-
gio_dim


- Joined on 03-16-2004

- Points 5
|
Imports System.IO
Imports System.Diagnostics
Imports System.ServiceProcess
Public Class Service1
Inherits System.ServiceProcess.ServiceBase
Public watchfolder As FileSystemWatcher
#Region " Component Designer generated code "
Public Sub New()
MyBase.New()
' This call is required by the Component Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call
End Sub
'UserService overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
' The main entry point for the process
<MTAThread()> _
Shared Sub Main()
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
' More than one NT Service may run within the same process. To add
' another service to this process, change the following line to
' create a second service object. For example,
'
' ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
'
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End Sub
'Required by the Component Designer
Private components As System.ComponentModel.IContainer
' NOTE: The following procedure is required by the Component Designer
' It can be modified using the Component Designer.
' Do not modify it using the code editor.
Friend WithEvents Timer1 As System.Windows.Forms.Timer
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Me.Timer1 = New System.Windows.Forms.Timer(Me.components)
'
'Timer1
'
Me.Timer1.Enabled = True
Me.Timer1.Interval = 1
'
'Service1
'
Me.ServiceName = "Service1"
End Sub
#End Region
Public Function StopWatch()
watchfolder.EnableRaisingEvents = False
WriteToFile("Service Stopped.")
End Function
Public Function StartWatch()
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
WriteToFile("Setting Folder to watch... ")
watchfolder = New System.IO.FileSystemWatcher("C:\mypath")
WriteToFile("""" & watchfolder.Path & """" & vbNewLine & "Done" & vbNewLine)
'this is the path we want to monitor
'watchfolder.Path = "C:\mypath"
' watchfolder.Path = txt_watchpath.Text
'Add a list of Filter we want to specify
'make sure you use OR for each Filter as we need to
'all of those
'WriteToFile("01")
watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes
' add the handler to each event
AddHandler watchfolder.Changed, AddressOf logchange
AddHandler watchfolder.Created, AddressOf logchange
AddHandler watchfolder.Deleted, AddressOf logchange
' add the rename handler as the signature is different
AddHandler watchfolder.Renamed, AddressOf logrename
'Set this property to true to start watching
watchfolder.EnableRaisingEvents = True
'End of code for btn_start_click
End Function
Public Function WriteToFile(ByVal pr_String As String)
FileOpen(1, "C:\temp\Log.log", OpenMode.Append)
Print(1, pr_String)
pr_String = ""
FileClose(1)
End Function
Public Sub logrename(ByVal source As Object, ByVal e As System.IO.RenamedEventArgs)
WriteToFile("File" & e.OldName & " has been renamed to " & e.Name & vbCrLf)
'txt_folderactivity.Text &= "File" & e.OldName & _
'" has been renamed to " & e.Name & vbCrLf
End Sub
Private Sub logchange(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
WriteToFile("File " & e.FullPath & " has been modified" & vbCrLf)
'txt_folderactivity.Text &= "File " & e.FullPath & _
'" has been modified" & vbCrLf
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
WriteToFile("File " & e.FullPath & " has been created" & vbCrLf)
'txt_folderactivity.Text &= "File " & e.FullPath & _
'" has been created" & vbCrLf
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
WriteToFile("File " & e.FullPath & " has been deleted" & vbCrLf)
'txt_folderactivity.Text &= "File " & e.FullPath & _
'" has been deleted" & vbCrLf
End If
End Sub
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code h
|
|
-
-
pjay23


- Joined on 06-10-2005

- Points 20
|
i want to perform a action when a file is generate
i liked the folder watch very much... to use it more appropriately i just wanted to implement to unzip files once a folder receives any kind of zip files ...
i tried
Private Sub logchange(ByVal source As Object, ByVal e As _
System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
txt_folderactivity.Text &= "File " & e.FullPath & _
" has been modified" & vbCrLf
ExecuteApplication("C:\WinRAR\WinRAR.exe x <source> <destn>
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
txt_folderactivity.Text &= "File " & e.FullPath & _
" has been created" & vbCrLf
ExecuteApplication("C:\WinRAR\WinRAR.exe x <source> <destn>
End If
If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
txt_folderactivity.Text &= "File " & e.FullPath & _
" has been deleted" & vbCrLf
ExecuteApplication("C:\WinRAR\WinRAR.exe x <source> <destn>
End If
End Sub
Public Sub ExecuteApplication(ByVal pstrApplicationName As String)
Dim udtProcess As Process = New Process
udtProcess.Start(pstrApplicationName)
udtProcess.Close()
End Sub
It doesnt work ... it opens the winrar and hangs up....
where do i go wrong in giving the command line syntax for unzipping ... and one more thing is it opens the winrar application which i think should work in the background like it does when i paste the command in START->RUN
thanks in anticipation Jayesh
|
|
-
-
-
-
-
jmurdock


- Joined on 07-07-2005

- Points 10
|
Quote:[1]Posted by jwillis27640 on 12 Jul 2005 05:14 PM[/1]
What are you doing with your service? I need the same type of thing but I need to parse the xml and sent it to SQL server. I have done this in vbscript not a problem but I cannot seem to get it to work in VB.net I get cross thread errors. jwillis27640@troy.edu
I am doing exactly what you are doing. I resolved my file locked issue by doing this:
<code>
Do While IO.File.GetAttributes(strFileName) = FileAttributes.Offline
'Wait 1/2 second before trying again.
Threading.Thread.Sleep(500)
Loop
Threading.Thread.Sleep(500)
fnReadXML(strFileName)
</code>
fnReadXML works like this:
<code>
Function fnReadXML(ByVal strFileName As String)
Dim fStream As New FileStream(strFileName, FileMode.Open)
Dim reader As XmlTextReader = New XmlTextReader(fStream)
Dim dsPO As New DataSet
Dim cError As New CustomError
Dim cErrors As CustomError()
Try
dsPO.ReadXml(reader)
reader.Close()
fStream.Close()
'Data Set has 2 tables, form relationship.
fnMakeRelationship(dsPO)
'Now that there is a dataset, use it to do my insert into SQL. Return errors if there are any.
cErrors = fnInsertPOFromDS(dsPO, strFileName)
Catch ex As Exception
EventLog.WriteEntry(Me.ServiceName, Me.ServiceName & " XMLTextReader " & ex.ToString, EventLogEntryType.Error)
End Try
reader = Nothing
dsPO.Dispose()
File.Delete(strFileName)
</code>
|
|
-
-
-
tlombardi


- Joined on 09-26-2005
- United States

- Points 5
|
Running this code as a service
Hi I have tried this code to use it for watching a folder for tif files which I wish to print automatically. I have managed to get it to work in an application mode. However I cant seem to make it work as a service.
I have included eventlog entries in the found new file handlers however nothing gets logged to the eventlog.
below is the code: where have i gone wrong?
Imports System.io
Imports System.IO.FileSystemWatcher
Imports System.diagnostics
Imports System.Drawing.Printing
Imports System.ServiceProcess
Public Class folderWatch
Inherits System.ServiceProcess.ServiceBase
Public VARwatchfolder As FileSystemWatcher
Public mapImage As System.Drawing.Bitmap
Dim folderToWatch As String = "C:\folderWatchTest"
#Region " Component Designer generated code "
Public Sub New()
MyBase.New()
' This call is required by the Component Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call
End Sub
'UserService overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
' The main entry point for the process
<MTAThread()> _
Shared Sub Main()
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
' More than one NT Service may run within the same process. To add
' another service to this process, change the following line to
' create a second service object. For example,
'
' ServicesToRun = New System.ServiceProcess.ServiceBase () {New folderWatch, New MySecondUserService}
'
ServicesToRun = New System.ServiceProcess.ServiceBase() {New folderWatch}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End Sub
'Required by the Component Designer
Private components As System.ComponentModel.IContainer
' NOTE: The following procedure is required by the Component Designer
' It can be modified using the Component Designer.
' Do not modify it using the code editor.
Friend WithEvents Timer1 As System.Windows.Forms.Timer
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Me.Timer1 = New System.Windows.Forms.Timer(Me.components)
'
'Timer1
'
Me.Timer1.Enabled = True
Me.Timer1.Interval = 1
'
'folderWatch
'
Me.ServiceName = "folderWatch"
End Sub
#End Region
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.
folderWatch()
System.Diagnostics.EventLog.WriteEntry("folderWatch", "FolderWatch service started!!! watching folder: " & folderToWatch)
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
VARwatchfolder.EnableRaisingEvents = False
End Sub
Public Function folderWatch()
'System.Diagnostics.EventLog.WriteEntry("folderWatch", "folderWatch Subroutine starts here")
'monitorTimer.Start()
VARwatchfolder = New System.IO.FileSystemWatcher
VARwatchfolder.Path = folderToWatch
VARwatchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
VARwatchfolder.NotifyFilter = VARwatchfolder.NotifyFilter Or _
IO.NotifyFilters.FileName
VARwatchfolder.NotifyFilter = VARwatchfolder.NotifyFilter Or _
IO.NotifyFilters.Attributes
'VARwatchfolder.Filter = "*.tif"
AddHandler VARwatchfolder.Created, AddressOf logCreate
AddHandler VARwatchfolder.Changed, AddressOf logCreate
VARwatchfolder.EnableRaisingEvents = True
End Function
Private Sub logCreate(ByVal Source As Object, ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
System.Diagnostics.EventLog.WriteEntry("folderWatch_change", "Found change in file: " & e.FullPath)
End If
If e.ChangeType = IO.WatcherChangeTypes.Created Then
System.Diagnostics.EventLog.WriteEntry("folderWatch_new", "Found New file: " & e.FullPath)
Dim imageFile As New System.Drawing.Bitmap(e.FullPath)
mapImage = imageFile
Dim printer As String = PrinterSettings.InstalledPrinters.Item(0)
Dim pd As New PrintDocument
AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage
pd.Print()
mapImage.Dispose()
System.Diagnostics.EventLog.WriteEntry("folderWatch_print", "Printed New file: " & e.FullPath)
Dim printedFilesPath As String
printedFilesPath = Replace(e.FullPath, folderToWatch, folderToWatch & "\printed")
' If CBmoveAfterPrint.Checked = True Then
System.IO.File.Move(e.FullPath, printedFilesPath)
System.Diagnostics.EventLog.WriteEntry("folderWatch", "will move file to " & printedFilesPath)
' &
|
|
-
-
wduros1


- Joined on 12-04-2005

- Points 10
|
Although the file watcher provides notification of a file create, it provides this notification at the moment of the file "creation", not the moment of the file "completion" if you know what I mean. If I create a file, then wait two minutes and write data into the file, then wait another two minutes and close the file, file watch will fire the create event on the file create, not four minutes after, when the file is closed. Even worse, if you create the file but close it. The later open it and write data and close.
This is an old problem with watching for files. The question "How do I know that the file is finished creating?" has the same answer as "How do I know the cake is finished baking?". You can time it, check it, and when you think it's done try to eat it, if it's not done, put it back in the oven...
What I usually do is add the file path and file size to a list, and then wait a period of time. When the time has elapsed, I compare the current file size against the earlier file size. When the file size has not changed for two subsequent checks, I "Assume" the file is done.
This method is, of course, flawed, since a network outage, or a slow connection, or an Application that writes in stages, etc. etc. could break it. I wish that there was a more definitive way to know. The secret to making this work in all conditions is to be able to spit the file back out if it's not "done". (Try to eat the cake, and if it's not done, put it back in the oven and continue to wait.)
|
|
-
Page 1 of 1 (15 items)
|
Search
Code Samples
New Members
|