Search code examples
visual-studio-2010filesystemwatcher

FileSystemWatcher Not Triggering Correctly


Alright my filesystemwatcher is not triggering until the first item in my listbox is present. The files listed in the listbox will not be created in that order though.

Further explaination...

I'm taking the value entered in a textbox, and adding that value to a listbox and changing an icon next to that value in a picture box. The icon will alert the user that the PDF hasn't been created yet.

    ListBox1.Items.Add(TextBoxTicketID.Text)

    If CStr(ListBox1.Items(0)) = TextBoxTicketID.Text Then
        PictureBoxStatus1.Image = My.Resources.Orange_Information
    ElseIf (ListBox1.Items(1)) = TextBoxTicketID.Text Then
        PictureBoxStatus2.Image = My.Resources.Orange_Information
    ElseIf (ListBox1.Items(2)) = TextBoxTicketID.Text Then
        PictureBoxStatus3.Image = My.Resources.Orange_Information
    End If

    TextBoxTicketID.Text = ""

    Call CheckPDFs()

The following is how I'm currently checking to see if the PDF has been created.

Eventually, in the private sub where the msgbox is at, I want to update the icon next to the ID to a green check mark, indicating the PDF has been created.

Public Sub CheckPDFs()
    Dim x As Integer
    Dim Watcher As New FileSystemWatcher()
    Watcher.Path = "C:\Temp\"
    Watcher.NotifyFilter = (NotifyFilters.Attributes)
    Watcher.Filter = ListBox1.Items(x) + ".pdf"

    AddHandler Watcher.Changed, AddressOf OnChanged

    Watcher.EnableRaisingEvents = True
End Sub

Private Shared Sub OnChanged(source As Object, e As FileSystemEventArgs)
    Dim x As Integer
    ' Specify what is done when a file is created.
    MsgBox("File has been created!")
End Sub

When I run the test, I created two unigue IDs entered into the listbox.

Issue1: I create a PDF manually by the first ID I entered, nothing triggers. I have to move the PDF out of the directory and back into before it triggers the msgbox.

Issue2: If I entered says two IDs, I create the second ID manually, nothing triggers. I move the file out of the directory and back in, still not triggering.

Why does the first ID need to be present before triggering any ID entered after it?

EDIT

Here two screenshot, before a user enters and after, showing the IDs entered and the icon.

Before_IDs_Entered

After_IDs_Entered


Solution

  • Your code does not show how you have your Watcher.NofityFilter set. If you want an event raised when a file is finished being written - and is ready to be used - then you must set it as follows:

    Watcher.NotifyFilter = NotifyFilters.Attributes;
    

    Then remove the Watcher.Created event you have listed; you want to have only the Changed. Otherwise you will receive two events: one for the file being created with zero bytes in it, and the other for when the file is done being written. I believe you only care when the file is done being written.