13 Replies - 2035 Views - Last Post: 28 October 2010 - 06:19 PM Rate Topic: -----

#1 Wenlong88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 03-October 10

DriveType and FileSystemWatcher

Posted 27 October 2010 - 11:34 PM

Hi all,

I seriously need some enlightenment.

Currently my code is only able to grab the first drive and do watcher.

I would want the program to be able to not only detect and use the first drive and do watcher, if there are more than 1 drive the program must be able to do the watcher together too.

Any idea how am i suppose to do it?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Temp.IO;

namespace FileWatcherTest
{
    class Program
    {

        public Program()
        {
        }
        static void Main(string[] args)
        {
                DriveInfo[] allDrives = DriveInfo.GetDrives();
                foreach (DriveInfo d in allDrives)
                {
                    Console.WriteLine("Drive {0}", d.Name);
                    Console.WriteLine("  File type: {0}", d.DriveType);


                    if (d.DriveType.ToString() == "Removable")
                    {

                        MyFileSystemWatcher fsw = new MyFileSystemWatcher(d.Name);

                        //MyFileSystemWatcher fsw = new MyFileSystemWatcher(@"C:\");
                        // fsw.Path = "C:\\temp";
                        fsw.IncludeSubdirectories = true;
                        fsw.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.FileName | NotifyFilters.DirectoryName;

                        fsw.Filter = "*.*";

                        fsw.Changed += new System.IO.FileSystemEventHandler(onchanged);
                        fsw.Created += new System.IO.FileSystemEventHandler(OnCreated);
                        fsw.Deleted += new System.IO.FileSystemEventHandler(OnDeleted);
                        fsw.Renamed += new System.IO.RenamedEventHandler(OnRenamed);

                        fsw.EnableRaisingEvents = true;

                        Console.WriteLine("Listening for changes in 'C:\\temp' directory...press any key to exit");
                        Console.Read();
                    } else 
                    
                    {
                        Console.WriteLine("No Removable Drive detected");
                    }
                }        

        }
        //private static void onchanged(object sender, System.IO.FileSystemEventArgs e) {
        //    Console.Write("\r\nFile: {0} {1} {2} {3}", e.FullPath, e.ChangeType, e.Name,DateTime.Now);
        //}
        static void OnRenamed(object sender, System.IO.RenamedEventArgs e)
        {
            Console.WriteLine("Renamed: FileName - {0}, ChangeType - {1}, Old FileName - {2}, Time - {3}", e.Name, e.ChangeType, e.OldName, DateTime.Now);                   
        }

        static void OnDeleted(object sender, System.IO.FileSystemEventArgs e)
        {
            Console.WriteLine("Deleted: FileName - {0}, ChangeType - {1}, Time - {2}", e.Name, e.ChangeType, DateTime.Now);
        }

        static void onchanged(object sender, System.IO.FileSystemEventArgs e)
        {
            Console.WriteLine("Changed: FileName - {0}, ChangeType - {1}, Time - {2}", e.Name, e.ChangeType, DateTime.Now);
        }

        static void OnCreated(object sender, System.IO.FileSystemEventArgs e)
        {   
            Console.WriteLine("Created: FileName - {0}, ChangeType - {1}, Time - {2}", e.Name, e.ChangeType, DateTime.Now);
        }


    }
}





Is This A Good Question/Topic? 0
  • +

Replies To: DriveType and FileSystemWatcher

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5466
  • View blog
  • Posts: 11,742
  • Joined: 02-June 10

Re: DriveType and FileSystemWatcher

Posted 27 October 2010 - 11:41 PM

Quote

MyFileSystemWatcher fsw = new MyFileSystemWatcher(d.Name);


We have no idea what your custom class "MyFileSystemWatcher" contains. You didn't include that code.

My guess is you have a bunch of static methods in it, or maybe even made the class static, and so no matter how many new instances you are making you get the one and only static class or method back.

also you need to make all your methods here NOT static. There is no reason for it.
Do you know what hte static qualifier means/does? Read up on it.

http://msdn.microsof...0hc(VS.80).aspx
Was This Post Helpful? 1
  • +
  • -

#3 Wenlong88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 03-October 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 12:10 AM

View PosttlhIn, on 27 October 2010 - 10:41 PM, said:

Quote

MyFileSystemWatcher fsw = new MyFileSystemWatcher(d.Name);


We have no idea what your custom class "MyFileSystemWatcher" contains. You didn't include that code.

My guess is you have a bunch of static methods in it, or maybe even made the class static, and so no matter how many new instances you are making you get the one and only static class or method back.

also you need to make all your methods here NOT static. There is no reason for it.
Do you know what hte static qualifier means/does? Read up on it.

http://msdn.microsof...0hc(VS.80).aspx



Guess you are the only one who willing to reply me. :)

haha..Thanks in advance.

ya, I know about static. Cos in school that what my teacher taught me. lolx.

How to make it not static? lolx.
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5466
  • View blog
  • Posts: 11,742
  • Joined: 02-June 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 12:16 AM

View PostWenlong88, on 27 October 2010 - 11:10 PM, said:

Guess you are the only one who willing to reply me. :)

haha..Thanks in advance.

ya, I know about static. Cos in school that what my teacher taught me. lolx.

How to make it not static? lolx.



Well - I'm one of the few probably awake, on-line, and doing my own coding at 0015hrs.

To make them not static, remove all the uses of the word static.
Was This Post Helpful? 0
  • +
  • -

#5 Wenlong88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 03-October 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 12:19 AM

View PosttlhIn, on 27 October 2010 - 11:16 PM, said:

View PostWenlong88, on 27 October 2010 - 11:10 PM, said:

Guess you are the only one who willing to reply me. :)

haha..Thanks in advance.

ya, I know about static. Cos in school that what my teacher taught me. lolx.

How to make it not static? lolx.



Well - I'm one of the few probably awake, on-line, and doing my own coding at 0015hrs.

To make them not static, remove all the uses of the word static.



I was able to post.

I tried removing all static. Except for my main. correct right?
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5466
  • View blog
  • Posts: 11,742
  • Joined: 02-June 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 12:24 AM

View PostWenlong88, on 27 October 2010 - 11:19 PM, said:

I tried removing all static. Except for my main. correct right?


Here's where experimenting will teach you. Its right, if it works when you run it. Did you run it after the changes? Did it work?
Was This Post Helpful? 0
  • +
  • -

#7 Wenlong88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 03-October 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 12:27 AM

View PosttlhIn, on 27 October 2010 - 11:24 PM, said:

View PostWenlong88, on 27 October 2010 - 11:19 PM, said:

I tried removing all static. Except for my main. correct right?


Here's where experimenting will teach you. Its right, if it works when you run it. Did you run it after the changes? Did it work?


I don think I can remove the static.

- An object reference is required for the non-static field, method, or property 'FileWatcherTest.Program.OnRenamed(object, System.IO.RenamedEventArgs)'

- \Documents\Visual Studio 2010\Projects\FileWatcherTest\FileWatcherTest\obj\x86\Debug\FileWatcherTest.exe' does not contain a static 'Main' method suitable for an entry point FileWatcherTest

These are the errors I got when I remove.
Was This Post Helpful? 0
  • +
  • -

#8 Wenlong88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 03-October 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 12:55 AM

View PostWenlong88, on 27 October 2010 - 11:27 PM, said:

View PosttlhIn, on 27 October 2010 - 11:24 PM, said:

View PostWenlong88, on 27 October 2010 - 11:19 PM, said:

I tried removing all static. Except for my main. correct right?


Here's where experimenting will teach you. Its right, if it works when you run it. Did you run it after the changes? Did it work?


I don think I can remove the static.

- An object reference is required for the non-static field, method, or property 'FileWatcherTest.Program.OnRenamed(object, System.IO.RenamedEventArgs)'

- \Documents\Visual Studio 2010\Projects\FileWatcherTest\FileWatcherTest\obj\x86\Debug\FileWatcherTest.exe' does not contain a static 'Main' method suitable for an entry point FileWatcherTest

These are the errors I got when I remove.


I am thinking about doing a array for fsw. But I do not know how and will it works?
Was This Post Helpful? 0
  • +
  • -

#9 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5466
  • View blog
  • Posts: 11,742
  • Joined: 02-June 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 12:57 AM

Post the code for your MyFileSystemWatcher class, please
Was This Post Helpful? 0
  • +
  • -

#10 Wenlong88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 03-October 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 01:06 AM

View PosttlhIn, on 27 October 2010 - 11:57 PM, said:

Post the code for your MyFileSystemWatcher class, please


sorry

using System;
using System.Collections.Generic;
using System.IO;
using System.ComponentModel;
using Temp.IO;

namespace Temp.IO
{
    public class MyFileSystemWatcher : FileWatcherTest, IDisposable
    {
        #region Private Members
        // This Dictionary keeps the track of when an event occured last for a particular file
        private Dictionary<string, DateTime> _lastFileEvent;
        // Interval in Millisecond
        private int _interval;
        //Timespan created when interval is set
        private TimeSpan _recentTimeSpan;
        #endregion

        #region Constructors
        // Constructors delegate to the base class constructors and call private InitializeMember method
        public MyFileSystemWatcher()
            : base()
        {
            InitializeMembers();
        }

        public MyFileSystemWatcher(string Path)
            : base(Path)
        {
            InitializeMembers();
        }

        public MyFileSystemWatcher(string Path, string Filter)
            : base(Path, Filter)
        {
            InitializeMembers();
        }
        #endregion

        #region Events
        // These events hide the events from the base class. 
        // We want to raise these events appropriately and we do not want the 
        // users of this class subscribing to these events of the base class accidentally
        public new event FileSystemEventHandler Changed;
        public new event FileSystemEventHandler Created;
        public new event FileSystemEventHandler Deleted;
        public new event RenamedEventHandler Renamed;
        #endregion

        #region Protected Methods
        // Protected Methods to raise the Events for this class
        protected new virtual void onchanged(FileSystemEventArgs e)
        {
            if (Changed != null) Changed(this, e);
        }

        protected new virtual void OnCreated(FileSystemEventArgs e)
        {
            if (Created != null) Created(this, e);
        }

        protected new virtual void OnDeleted(FileSystemEventArgs e)
        {
            if (Deleted != null) Deleted(this, e);
        }

        protected new virtual void OnRenamed(RenamedEventArgs e)
        {
            if (Renamed != null) Renamed(this, e);
        }
        #endregion

        #region Private Methods

        /// <summary>
        /// This Method Initializes the private members.
        /// Interval is set to its default value of 100 millisecond
        /// FilterRecentEvents is set to true, _lastFileEvent dictionary is initialized
        /// We subscribe to the base class events.
        /// </summary>
        private void InitializeMembers()
        {
            Interval = 100;
            FilterRecentEvents = true;
            _lastFileEvent = new Dictionary<string, DateTime>();

            base.Created += new FileSystemEventHandler(OnCreated);
            base.Changed += new FileSystemEventHandler(onchanged);
            base.Deleted += new FileSystemEventHandler(OnDeleted);
            base.Renamed += new RenamedEventHandler(OnRenamed);
        }

        /// <summary>
        /// This method searches the dictionary to find out when the last event occured 
        /// for a particular file. If that event occured within the specified timespan
        /// it returns true, else false
        /// </summary>
        /// <param name="FileName">The filename to be checked</param>
        /// <returns>True if an event has occured within the specified interval, False otherwise</returns>
        private bool HasAnotherFileEventOccuredRecently(string FileName)
        {
            bool retVal = false;

            // Check dictionary only if user wants to filter recent events otherwise return Value stays False
            if (FilterRecentEvents)
            {
                if (_lastFileEvent.ContainsKey(FileName))
                {
                    // If dictionary contains the filename, check how much time has elapsed
                    // since the last event occured. If the timespan is less that the 
                    // specified interval, set return value to true 
                    // and store current datetime in dictionary for this file
                    DateTime lastEventTime = _lastFileEvent[FileName];
                    DateTime currentTime = DateTime.Now;
                    TimeSpan timeSinceLastEvent = currentTime - lastEventTime;
                    retVal = timeSinceLastEvent < _recentTimeSpan;
                    _lastFileEvent[FileName] = currentTime;
                }
                else
                {
                    // If dictionary does not contain the filename, 
                    // no event has occured in past for this file, so set return value to false
                    // and annd filename alongwith current datetime to the dictionary
                    _lastFileEvent.Add(FileName, DateTime.Now);
                    retVal = false;
                }
            }

            return retVal;
        }

        #region FileSystemWatcher EventHandlers
        // Base class Event Handlers. Check if an event has occured recently and call method
        // to raise appropriate event only if no recent event is detected
        private void onchanged(object sender, FileSystemEventArgs e)
        {
            if (!HasAnotherFileEventOccuredRecently(e.FullPath))
                this.onchanged(e);
        }

        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            if (!HasAnotherFileEventOccuredRecently(e.FullPath))
                this.OnCreated(e);
        }

        private void OnDeleted(object sender, FileSystemEventArgs e)
        {
            if (!HasAnotherFileEventOccuredRecently(e.FullPath))
                this.OnDeleted(e);
        }

        private void OnRenamed(object sender, RenamedEventArgs e)
        {
            if (!HasAnotherFileEventOccuredRecently(e.OldFullPath))
                this.OnRenamed(e);
        }
        #endregion
        #endregion

        #region Public Properties

        /// <summary>
        /// Interval, in milliseconds, within which events are considered "recent"
        /// </summary>
        public int Interval
        {
            get
            {
                return _interval;
            }
            set
            {
                _interval = value;
                // Set timespan based on the value passed
                _recentTimeSpan = new TimeSpan(0, 0, 0, 0, value);
            }
        }

        /// <summary>
        /// Allows user to set whether to filter recent events. If this is set a false,
        /// this class behaves like System.IO.FileSystemWatcher class
        /// </summary>
        public bool FilterRecentEvents { get; set; }
        #endregion

        #region IDisposable Members

        public new void Dispose()
        {
            base.Dispose();
        }

        #endregion
    }
}




Was This Post Helpful? 0
  • +
  • -

#11 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5466
  • View blog
  • Posts: 11,742
  • Joined: 02-June 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 01:30 AM

Quote

public class MyFileSystemWatcher : FileWatcherTest, IDisposable


Huh? You're trying to create your class by inheriting from your other namespace?

Quote

namespace FileWatcherTest


Generally a custom class inherits from the more generalize class. If I make a custom textbox that only accepts numbers, then I inherit from the standard textbox, then customize it
public class NumericOnlyTextbox : Textbox

Anyway, so this is acting as a debounce filter for the FileSystemWatcher events. If the same event like a Changed takes place in rapid succession you only raise one event. Is that right?

The problem with this is that you will raise an event on the first occurance but not on the last/most-recent.

private void onchanged(object sender, FileSystemEventArgs e)
        {
            if (!HasAnotherFileEventOccuredRecently(e.FullPath))
                this.onchanged(e);
        }


So you'll raise the changed event as soon as a file starts changing (being written), but not when the changes stop taking place. Your subscriber is going to be alerted early instead of when the file is idle/ready.


Quote

I am thinking about doing a array for fsw. But I do not know how and will it works?


List<MyFileSystemWatcher) FSWlist = new List<MyFileSystemWatcher();

Try it and find out.
Was This Post Helpful? 1
  • +
  • -

#12 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4453
  • View blog
  • Posts: 7,755
  • Joined: 08-June 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 07:00 AM

In a console app, methods being called from the Main method have to be static, because Main has to be static. So do all properties and fields it accesses.
Was This Post Helpful? 1
  • +
  • -

#13 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5466
  • View blog
  • Posts: 11,742
  • Joined: 02-June 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 09:32 AM

View PostinsertAlias, on 28 October 2010 - 06:00 AM, said:

In a console app, methods being called from the Main method have to be static, because Main has to be static. So do all properties and fields it accesses.


Really? I didn'tknow that. I don't build console apps. Never have. Hmmm... I have on a couple occasions built a WindowsForms app, then changed its type in the project properties to console, for debugging purposes. That way I have a GUI application that keeps a console window open for easy debugging Console.WriteLine("Status Report: You broke it here");

I apologize for steering the OP in the wrong direction because I was talking out of my ... hat about removing the static calls.
Was This Post Helpful? 0
  • +
  • -

#14 Wenlong88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 03-October 10

Re: DriveType and FileSystemWatcher

Posted 28 October 2010 - 06:19 PM

View PosttlhIn, on 28 October 2010 - 08:32 AM, said:

View PostinsertAlias, on 28 October 2010 - 06:00 AM, said:

In a console app, methods being called from the Main method have to be static, because Main has to be static. So do all properties and fields it accesses.


Really? I didn'tknow that. I don't build console apps. Never have. Hmmm... I have on a couple occasions built a WindowsForms app, then changed its type in the project properties to console, for debugging purposes. That way I have a GUI application that keeps a console window open for easy debugging Console.WriteLine("Status Report: You broke it here");

I apologize for steering the OP in the wrong direction because I was talking out of my ... hat about removing the static calls.



Haha. Its ok. I have solve my array problem already.
Nah! Its ok You have help me quite a bit.
Guess soon will have problem again, as I am converting from console to service. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1