1

I don't know how to integrate the code I wrote on c# with the FileSystemWatcher class

    public static void watcherFunc()
    {
        FileSystemWatcher fileWatcher = new FileSystemWatcher(@"C:\Documents and Settings\Develop\Desktop\test\");
        fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
        fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
        fileWatcher.EnableRaisingEvents = true;
    }
    // Define the event handlers. 
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
        MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
    }

I tried to call it in form1 lead event.... I tried to read how to do it and google it with no luck please help...thank you !

2
  • i have not used c# in a while, but if you declare a watcher in a function, isn't it out of scope when that function finishes? Commented Jul 29, 2013 at 20:51
  • Well I guess it is what happens =) sound logic when you say it Commented Jul 29, 2013 at 21:10

1 Answer 1

3

From what I can tell the problem is that your FileSystemWatcher goes out of scope when you finish the method. Therefore it is no longer active for you to catch events.

Try it like so:

FileSystemWatcher fileWatcher = new FileSystemWatcher(@"C:\Documents and ettings\Develop\Desktop\test\");
public void Initialize() //initialization or Constructor
{
    fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
    fileWatcher.Changed += new FileSystemEventHandler(OnChanged);
    fileWatcher.EnableRaisingEvents = true;
}

// Define the event handlers. 
private void OnChanged(object source, FileSystemEventArgs e)
{
    // Specify what is done when a file is changed, created, or deleted.
    MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
}

See FileWatcher Tutorial for more help if you need it

Sign up to request clarification or add additional context in comments.

4 Comments

still not working i tried it with your code + I saw the tutorial and tried to do it in that way and still nothing no error and no result
I can add a timer maybe it will work but it isnt good for me I want a live monitoring not every 5 min...
ok I switched the OnChanged event to Created event and now it works but I still don't understand why it didn't work with the OnChanged
I can't seem to replicate your issue. This is what I used: pastebin.com/wZYiDq54. When I open a notepad file and save it in that directory, the messagebox shows up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.