none
filesystemwatcher not firing unless i refresh the dir RRS feed

  • Question

  • Hi guys im using filesystemwatcer in my app. Its suppose to read and display in a textbox the content of a logfile(the last updated lines) but i notice that if i dont press F5 where the log reside it dosen't update. did i miss some code here? or is there such code that will also simulate f5 of a given path?
    Saturday, December 3, 2011 6:07 PM

Answers

All replies

  • Hi Niel,

    Could you please show the code you use to create the FileSystemWatcher?

     

    Edit

    I've put together an example here that works for me.

    First I create a new text-file in C:\temp that is called testfile.txt like this: 

    File.Create(@"C:\temp\testfile.txt").Close();
    

    Then I create my FileSystemWatcher and tell it to look in C:\temp for *.txt (all files that ends with .txt) and here is the special part, I tell the notify filter to check:

    • LastAccess
    • LastWrite
    • FileName
    • Directoryname

    Which means that if any of the above changes, my event will be raised, so that part look like this:

    var watch = new FileSystemWatcher
    {
        Path = @"C:\temp",
        NotifyFilter =
            NotifyFilters.LastAccess |
            NotifyFilters.LastWrite |
            NotifyFilters.FileName |
            NotifyFilters.DirectoryName,
        Filter = "*.txt"
    };
     
    watch.Changed += (_, __) => Console.WriteLine("File changed!");
     
    watch.EnableRaisingEvents = true;

    Keep in mind that I use anonymous functions and other things here just to clearify the example and only focus on the important parts.

    Now to test this out, I've got this in a Console Application and I fire off a Task/Thread that just updates the file every 500 millisecond and then I listen for a input so the Console Application does not quit:

    var fileUpdateTask = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            using (var writer = new StreamWriter(@"C:\temp\testfile.txt"true))
                writer.WriteLine(DateTime.Now);
     
            Thread.Sleep(500);
        }
    });
     
    Console.ReadLine();

    By running this, the Console will be "flooded" with "File changed!", text. Without me having to go into the folder pressing F5.

    I hope this helps


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se

    Saturday, December 3, 2011 11:08 PM
  • Hi Niel,

    Could you please show the code you use to create the FileSystemWatcher?


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se

    Hi Filip here you go.

     

     watcher.Path = @"C:\DR activity logs\_SENDER";

                watcher.NotifyFilter = NotifyFilters.LastAccess |

                                        NotifyFilters.LastWrite |

                                        NotifyFilters.FileName |

                                        NotifyFilters.DirectoryName;

                watcher.Filter = "*.log";

                watcher.Changed += new FileSystemEventHandler(OnChanged);

                watcher.Created += new FileSystemEventHandler(OnChanged);

                watcher.Deleted += new FileSystemEventHandler(OnChanged);

                watcher.Renamed += new RenamedEventHandler(OnRenamed);

     

     public void OnChanged(object source, FileSystemEventArgs e)

            {   this.Invoke((Action)delegate

                {

                    textBox2.Text = ReadEndTokens(textBox1.Text, 10, Encoding.ASCII, "\n");

                });

                    string sPattern = "Dec 03";

                    //string match = "(" + string.Join("|", sPattern);

     

                    for (int ctr = 0; ctr < textBox2.Lines.Length; ctr++)

                    {

                        Match match = Regex.Match(textBox2.Lines[ctr].ToString(), sPattern);

                        if (match.Success)

                        {

                            this.Invoke((Action)delegate

                            {

                                textBox3.AppendText(textBox2.Lines[ctr].ToString());

                            });

                            //send_text("alerts", "09082817245", textBox2.Lines[ctr].ToString());

                        }

                    }

     

                //});

     

                MessageBox.Show("OnChanged event");

            }

     


    • Edited by niel michael Saturday, December 3, 2011 11:21 PM
    Saturday, December 3, 2011 11:21 PM
  • Hi Niel,

    Could you please show the code you use to create the FileSystemWatcher?

     

    Edit

    I've put together an example here that works for me.

    First I create a new text-file in C:\temp that is called testfile.txt like this: 

    File.Create(@"C:\temp\testfile.txt").Close();
    

    Then I create my FileSystemWatcher and tell it to look in C:\temp for *.txt (all files that ends with .txt) and here is the special part, I tell the notify filter to check:

    • LastAccess
    • LastWrite
    • FileName
    • Directoryname

    Which means that if any of the above changes, my event will be raised, so that part look like this:

    var watch = new FileSystemWatcher
    {
        Path = @"C:\temp",
        NotifyFilter =
            NotifyFilters.LastAccess |
            NotifyFilters.LastWrite |
            NotifyFilters.FileName |
            NotifyFilters.DirectoryName,
        Filter = "*.txt"
    };
     
    watch.Changed += (_, __) => Console.WriteLine("File changed!");
     
    watch.EnableRaisingEvents = true;

    Keep in mind that I use anonymous functions and other things here just to clearify the example and only focus on the important parts.

    Now to test this out, I've got this in a Console Application and I fire off a Task/Thread that just updates the file every 500 millisecond and then I listen for a input so the Console Application does not quit:

    var fileUpdateTask = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            using (var writer = new StreamWriter(@"C:\temp\testfile.txt"true))
                writer.WriteLine(DateTime.Now);
     
            Thread.Sleep(500);
        }
    });
     
    Console.ReadLine();

    By running this, the Console will be "flooded" with "File changed!", text. Without me having to go into the folder pressing F5.

    I hope this helps


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se

    would that be appending another line inside my log file? but my log file is constantly generated from sercureCRT .?
    Sunday, December 4, 2011 12:32 AM
  • You say that the log file is constantly being generated. Is the program writing the log releasing the file handle, or is it open the whole time the program is running?
    Sunday, December 4, 2011 5:58 AM
  • would that be appending another line inside my log file? but my log file is constantly generated from sercureCRT .?

    Yes, it appends a line inside the file. But that doesn't matter since the flags tell it to look for everything.

    Did you try running my example? Did it work as you expected?


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se
    Sunday, December 4, 2011 10:09 AM
  • You say that the log file is constantly being generated. Is the program writing the log releasing the file handle, or is it open the whole time the program is running?

    its always opened by the program(SecureCRT). i using below code

     using (Stream fs = System.IO.File.Open(path,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)) so that i wont get the error that is being access by other program. Do you haveany idea?

    Sunday, December 4, 2011 12:35 PM

  •  

    would that be appending another line inside my log file? but my log file is constantly generated from sercureCRT .?

    Yes, it appends a line inside the file. But that doesn't matter since the flags tell it to look for everything.

    Did you try running my example? Did it work as you expected?


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se
    im getting Task does not exists i think because im using .net 3.5? how cant i fix this?
    Sunday, December 4, 2011 12:52 PM
  • Task was introduced in .NET 4.0, run this instead:

    using System;
    using System.IO;
    using System.Threading;
    
    namespace FileSystemWatcherTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                File.Create(@"C:\temp\testfile.txt").Close();
                var watch = new FileSystemWatcher
                {
                    Path = @"C:\temp",
                    NotifyFilter =
                        NotifyFilters.LastAccess |
                        NotifyFilters.LastWrite |
                        NotifyFilters.FileName |
                        NotifyFilters.DirectoryName,
                    Filter = "*.txt"
                };
    
                watch.Changed += (_, __) => Console.WriteLine("File changed!");
    
                watch.EnableRaisingEvents = true;
    
                var fileUpdateTask = new Thread(() =>
                {
                    while (true)
                    {
                        using (var writer = new StreamWriter(@"C:\temp\testfile.txt", true))
                            writer.WriteLine(DateTime.Now);
    
                        Thread.Sleep(500);
                    }
                });
    
                fileUpdateTask.Start();
    
                Console.ReadLine();
            }
        }
    }
    
    
    Hope this helps


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se
    Sunday, December 4, 2011 1:23 PM
  • Task was introduced in .NET 4.0, run this instead:

     

    using System;
    using System.IO;
    using System.Threading;
    
    namespace FileSystemWatcherTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                File.Create(@"C:\temp\testfile.txt").Close();
                var watch = new FileSystemWatcher
                {
                    Path = @"C:\temp",
                    NotifyFilter =
                        NotifyFilters.LastAccess |
                        NotifyFilters.LastWrite |
                        NotifyFilters.FileName |
                        NotifyFilters.DirectoryName,
                    Filter = "*.txt"
                };
    
                watch.Changed += (_, __) => Console.WriteLine("File changed!");
    
                watch.EnableRaisingEvents = true;
    
                var fileUpdateTask = new Thread(() =>
                {
                    while (true)
                    {
                        using (var writer = new StreamWriter(@"C:\temp\testfile.txt", true))
                            writer.WriteLine(DateTime.Now);
    
                        Thread.Sleep(500);
                    }
                });
    
                fileUpdateTask.Start();
    
                Console.ReadLine();
            }
        }
    }
    
    
    Hope this helps

     


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se

    Hey Filip! Ic thats why.. let me try it.. although i found another way i try to put the ff code inside a timer. then regardless if its updated or not it will keep on reading hehe. I know not the best/efficient approach hehe. but stilli want to learn your and try your idea!

     

    textBox2.Text = ReadEndTokens(textBox1.Text, 10, Encoding.ASCII, "\n");

                textBox2.SelectionStart = textBox2.Text.Length;

                textBox2.ScrollToCaret();

                textBox2.Refresh();

    Sunday, December 4, 2011 1:47 PM
  • Task was introduced in .NET 4.0, run this instead:

     

    using System;
    using System.IO;
    using System.Threading;
    
    namespace FileSystemWatcherTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                File.Create(@"C:\temp\testfile.txt").Close();
                var watch = new FileSystemWatcher
                {
                    Path = @"C:\temp",
                    NotifyFilter =
                        NotifyFilters.LastAccess |
                        NotifyFilters.LastWrite |
                        NotifyFilters.FileName |
                        NotifyFilters.DirectoryName,
                    Filter = "*.txt"
                };
    
                watch.Changed += (_, __) => Console.WriteLine("File changed!");
    
                watch.EnableRaisingEvents = true;
    
                var fileUpdateTask = new Thread(() =>
                {
                    while (true)
                    {
                        using (var writer = new StreamWriter(@"C:\temp\testfile.txt", true))
                            writer.WriteLine(DateTime.Now);
    
                        Thread.Sleep(500);
                    }
                });
    
                fileUpdateTask.Start();
    
                Console.ReadLine();
            }
        }
    }
    
    
    Hope this helps

     


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se

    Hey Filip! Ic thats why.. let me try it.. although i found another way i try to put the ff code inside a timer. then regardless if its updated or not it will keep on reading hehe. I know not the best/efficient approach hehe. but stilli want to learn your and try your idea!

     

     

    textBox2.Text = ReadEndTokens(textBox1.Text, 10, Encoding.ASCII, "\n");

                textBox2.SelectionStart = textBox2.Text.Length;

                textBox2.ScrollToCaret();

                textBox2.Refresh();

     

    im getting an error that is being used by another process. 
    Sunday, December 4, 2011 1:58 PM
  • When the log writer opens the file, does it open the file allowing other programs to read from it?

    Sunday, December 4, 2011 3:42 PM
  • When the log writer opens the file, does it open the file allowing other programs to read from it?

    basically im just taking advantage of the secureCRT which is the one that's generating the logfile then all i did was to read from that file to check if there area certain errors in this case i'll also use regex.

    but whats holding me back for finishing this is that filesystemwatcher doesnt work unless i press f5

    Sunday, December 4, 2011 3:51 PM
  • Refreshing the directory in explorer shouldn't have a direct affect on this at all. My best guess as to why it might would be that the log writer is keeping the logs in some buffer, and refreshing the directory causes enough I/O work to occur on the disk that the log writer decides to flush the buffer.
    Sunday, December 4, 2011 4:06 PM
  • im getting an error that is being used by another process. 

    From running my code and only my code? That is very weird, you shouldn't bet that error with that.
    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se
    Sunday, December 4, 2011 4:16 PM
  • im getting an error that is being used by another process. 

    From running my code and only my code? That is very weird, you shouldn't bet that error with that.
    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se
    yeah. is that because securecrt is always reading and updating the file?
    Sunday, December 4, 2011 4:46 PM
  • Refreshing the directory in explorer shouldn't have a direct affect on this at all. My best guess as to why it might would be that the log writer is keeping the logs in some buffer, and refreshing the directory causes enough I/O work to occur on the disk that the log writer decides to flush the buffer.
    Maybe. i also notice that the filesize/last modified is not updating even if securecrt is moving which is at the same time creating the log file. it will only after i press f5..
    Sunday, December 4, 2011 4:50 PM
  • It is most likely SecureCRT that blocks the file. If you create a new console application called FileSystemWatcherTest and paste the code that I posted above into that application and run it. Do you see another result?


    Mark good replies as helpful and correct ones as answers! - http://blog.filipekberg.se
    Sunday, December 4, 2011 6:06 PM
  • im getting an error that is being used by another process.
    yeah. is that because securecrt is always reading and updating the file?

    Hi niel michael,

    To resolve the issue,  I think we must use Synchronized thread and managed the threads in a ThreadingPool.

    If any one are processing the file, we must make the next thread wait for the previews task. On how to use the Thread Synchronization, see:

    http://msdn.microsoft.com/en-us/library/ms173179.aspx 

    On the other hand, when we use the FileStream, we need to Lock/UnLock the file, see:

    FileStream.Unlock Method:
    http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx

    FileStream.Lock Method:
    http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx

    If you have any questiosn, please feel free to tell us.

    Best Regards


    Neddy Ren[MSFT]
    MSDN Community Support | Feedback to us
    • Marked as answer by Neddy Ren Monday, December 19, 2011 9:27 AM
    Tuesday, December 6, 2011 7:32 AM
  • im getting an error that is being used by another process.

    yeah. is that because securecrt is always reading and updating the file?

    Hi niel michael,

    To resolve the issue,  I think we must use Synchronized thread and managed the threads in a ThreadingPool.

    If any one are processing the file, we must make the next thread wait for the previews task. On how to use the Thread Synchronization, see:

    http://msdn.microsoft.com/en-us/library/ms173179.aspx 

    On the other hand, when we use the FileStream, we need to Lock/UnLock the file, see:

    FileStream.Unlock Method:
    http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx

    FileStream.Lock Method:
    http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx

    If you have any questiosn, please feel free to tell us.

    Best Regards


    Neddy Ren[MSFT]
    MSDN Community Support | Feedback to us

    Once again, useless responses from Support reps.

    When will Microsoft stop incentivizing this sort of behavior in the forums? Maybe we should go back to the publicly-moderated newsgroups at this point so we don't have 1 bad answer for every unsolvable question.

    We don't need moderator responses, 99% of the time they are useless posts meant to reduce queues. *spit*

    end it.

    Friday, October 14, 2016 9:06 PM