ChristopherSirén
ChristopherSirén

Reputation: 139

FileSystemWatcher behaving inconsistently

I've set all the FSW properties in the designer (EnableRaisingEvents = true, filter = *.tif, IncludeSubdirectories = true, path = bla\bla\bla).

The application runs on a Windows Server 2008 R2 Standard machine and watches a local folder for created files. Instead of "C:\" i use the computers network name "GRAHAM".

The problem is that the FSW doesn't always fire when files are created/moved to the watched directory. It seems that sometimes it does, but most times it doesn't.

When debugging and watching that folder from my machine there is also some strange behaviour. If i remotely control the server machine and move files to the watched folder nothing happens. But if I move files into the watched folder from shared network folders the FSW fires, every time.

This makes it really hard for me to find the error/bug. Anyone got any ideas?

This is literally all of the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Ekonomikompetens_unikt_namn
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            StringBuilder log = new StringBuilder();

            try
            {
                log.Append("--------------------").AppendLine().Append(DateTime.Now).AppendLine().Append("--------------------").AppendLine();

                FileInfo file = new FileInfo(e.FullPath);

                while (IsFileLocked(file))
                {
                    System.Threading.Thread.Sleep(300);
                }
                string oFile = e.FullPath;
                string nFile = oFile.Insert(oFile.Length - 4, "_" + DateTime.Now.ToString().Replace(" ", "").Replace("-", "").Replace(":", "")).Replace("\\XML Konvertering", "").Replace(@"\\GRAHAM\AnyDoc Invoices", @"\\FAKTURASERVER\AnyDoc");

                if (!Directory.Exists(nFile.Substring(0, nFile.LastIndexOf('\\'))))
                {
                    Directory.CreateDirectory(nFile.Substring(0, nFile.LastIndexOf('\\')));
                    File.Move(oFile, nFile);
                    Directory.Delete(oFile.Substring(0, oFile.LastIndexOf('\\')));
                }
                else
                {
                    File.Move(oFile, nFile);
                }

                log.Append("* Moved and stamped file: ").AppendLine().Append(oFile).Append(" to ").Append(nFile).AppendLine().Append("--------------------").AppendLine();

            }
            catch (Exception x)
            {
                log.AppendLine().Append("*** ERROR *** ").Append(x).AppendLine().AppendLine();
            }
            finally
            {
                TextWriter tw = new StreamWriter(@"C:\tidslog\log.txt", true, Encoding.Default);
                //TextWriter tw = new StreamWriter(@"C:\PROJEKT\tidsstämplarn\log.txt", true, Encoding.Default);
                tw.Write(log);
                tw.Dispose();
            }
        }

        protected virtual bool IsFileLocked(FileInfo file)
        {
            FileStream stream = null;
            try
            {
                stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            return false;
        }
    }
}

Note: The try-catch-finally is probably not really well made, but I'm new to coding and not really sure how to "catch" stuff, the logger has never logged an error though. Since the FSW never fires there isn't a chance for an error to occur. I'm guessing.

Upvotes: 1

Views: 495

Answers (1)

Anirudha
Anirudha

Reputation: 32817

Subscribe to the Error event and check the error if any


In case there are large number of file being created or changed,do this

1> Increase InternalBufferSize.

Doc say this:

Increasing the size of the buffer can prevent missing file system change events. However, increasing buffer size is expensive, because it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small as possible. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties to filter out unwanted change notifications.

2> Also you are doing a lot of things in fileSystemWatcher1_Created which can cause the buffer to overflow causing it to miss some events...Use ThreadPool instead.

Upvotes: 3

Related Questions