0

It seems like my file system watcher is firing mulitple events and then ending up giving me an error:

The process cannot access the file, file is in use.

Here is my code:

 private void button1_Click(object sender, EventArgs e)
    {
       // Form2 popup = new Form2();
        if (Directory.Exists(this.textBox2.Text) && string.IsNullOrWhiteSpace(textBox2.Text))
        {
            MessageBox.Show("Please Select Source Folder");
            return;
        }

        else if (Directory.Exists(this.textBox3.Text) && string.IsNullOrWhiteSpace(textBox3.Text))
        {
            MessageBox.Show("Please Select Destination Folder");
            return;

        }
        else  WatchFile();

private void WatchFile(/*string watch_folder*/)
    {
        FileSystemWatcher _watcher = new FileSystemWatcher();

        _watcher.Path = textBox2.Text;




        _watcher.NotifyFilter = NotifyFilters.LastWrite;
        _watcher.Filter = "*.log";

        _watcher.Changed += new FileSystemEventHandler(InitList);
        _watcher.EnableRaisingEvents = true;
        _watcher.IncludeSubdirectories = false;


        listBox1.Items.Add("Started Monitoring Directory " + textBox2.Text);
        listBox1.SelectedIndex = listBox1.Items.Count - 1;
    }

    private  object lockObject = new Object();

    public  void InitList(object source, FileSystemEventArgs f)
    {
        _recordList = new List<MyData>();


        string fileName = f.FullPath;
        string filePath = f.Name;
        string trPath = fileName;
        string[] arrstringPath = new string[3];
        arrstringPath[0] = filePath.Substring(2, 2);
        arrstringPath[1] = filePath.Substring(4, 2);
        arrstringPath[2] = filePath.Substring(6, 2);
        string tempPath = "LG" + arrstringPath[0] + arrstringPath[1] + arrstringPath[2] + ".001";
        string v15nativePath = textBox3.Text + tempPath;

        _watcher.EnableRaisingEvents = false;

        if (!Monitor.TryEnter(lockObject))
        {
            return;
        }
        else
        try
        {

            //_watcher.EnableRaisingEvents = false;
            _watcher.Changed -= new FileSystemEventHandler(InitList);

            FileStream trFS = new FileStream(trPath, FileMode.Open, FileAccess.Read);
            StreamReader trSR = new StreamReader(trFS);

            //  FileStream v15FS = new FileStream(v15nativePath, FileMode.Open, FileAccess.Write);
            StreamWriter v15SR = new StreamWriter(v15nativePath, false);





            var timeIndex = "S";
            Func<string, MyData> values = new Func<string, MyData>(
                     (x) =>
                     {


                         if ((x[0].ToString()) == "S")
                         {

                             var temptime = x.IndexOf("S");
                             timeIndex = x.Substring(temptime + 1, 4);

                         }



                         if ((x[0].ToString()) == "C")
                         {
                             var trackIndex = x.IndexOf(":");

                             var titleidString = x.Substring(11, 6);
                             var trackString = x.Substring(17, 40);
                             var trackDuration = x.Substring(57, 5);

                             return new MyData { Time = timeIndex, Duration = trackDuration, TitleID = titleidString, Track = trackString };



                         }
                         else
                             return null;

                     });




            while (trSR.Peek() != -1)
            {
                var data = trSR.ReadLine();


                MyData my = values(data);
                if (my != null)
                    _recordList.Add(my);


            }
            trFS.Close();
            trSR.Close();

            var groupData = from data in _recordList
                            select new
                            {
                                Name = data.Track,
                                Duration = data.Duration,
                                Time = data.Time,
                                ID = data.TitleID

                            };



            foreach (var item in groupData)
            {
                                    var newstringLen = item.Name.Truncate(27);
                var v15timeString = item.Duration;
                var v15fileString = "C" + item.Time + ":" + "00" + item.ID + "         " + newstringLen + v15timeString;
            v15SR.WriteLine(v15fileString);
                v15SR.Flush();


            }
            v15SR.Close();


            this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(string.Format("File is Translated")); });

            _watcher.Changed += new FileSystemEventHandler(InitList);
        }
        catch (Exception e)
        {
            //listBox1.Items.Add("The process failed: "+" "+e.ToString());.
            MessageBox.Show("The Process Failed:" + e.ToString());


        }
        finally
        {
            Monitor.Exit(lockObject);
            _watcher.Path = textBox2.Text;

            _watcher.EnableRaisingEvents = true;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();



        }



    }

I have called _watcher.EnableRaisingEvents = false; before the try block and then make it true in the final block yet. the watching get's disabled while I do the processing then why does it run the InitList method again after it finishes. This seems like a mulitple run on the same file, and so causing this exception

user726720
  • 1,127
  • 7
  • 25
  • 59
  • 1
    You might want to go through the posts : http://stackoverflow.com/questions/9396651/filesystemwatcher-getting-too-many-event and http://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice – Sidhartha Shenoy Jun 08 '14 at 12:24
  • Yes, I have tried all sorts of things but they aren't working properly. I have also tried to enable _watcher.EnableRaisingEvents = false; and then back again to true after doing the job. This works well with the Console APplication but doesn't work properly with the Windows forms. Why is that ? – user726720 Jun 09 '14 at 03:45

0 Answers0