C # Use of FileSystemWatcher file monitoring objects

Source: Internet
Author: User

C # Use of filesystemwatcher file monitoring objects

Thread-safe hashtable is used to handle the problem of triggering two events with one change. Note that in actual project use, when a monitoring file is triggered and a thread watcherprocess is enabled to process its own business logic, no matter whether the business logic is successful or fails (for example, if an exception is thrown, try again) make sure that the watcherprocess completed, that is, the watcherprocess_oncompleted command of myfilesystemwather, is executed to remove the hashtable key of the changed file. Otherwise, your business logic will not be triggered when the file changes next time.

There is also an I/o conflict when the monitored file is written during file monitoring, even if the file to be written is fileshare. read will also appear. To solve this problem, it seems that only the filemaping method is available. However, we cannot control the text writing software in my project. Therefore, we only need to solve the problem by handling exceptions.

 

Using system;
Using system. io;

Namespace test
{
Class program
{
Static void main (string [] args)
{


Watcherstrat (@ "c: test", "*. txt ");
// Because it is a console program, add an input to avoid the completion of the main thread, and the monitoring effect is not visible.
Console. readkey ();

}

Private static void watcherstrat (string path, string filter)
{
Filesystemwatcher watcher = new filesystemwatcher ();
Watcher. path = path;

Watcher. filter = filter;

Watcher. changed + = new filesystemeventhandler (onprocess );
Watcher. created + = new filesystemeventhandler (onprocess );
Watcher. deleted + = new filesystemeventhandler (onprocess );
Watcher. renamed + = new renamedeventhandler (onrenamed );

Watcher. enableraisingevents = true;
}

 


Private static void onprocess (object source, filesystemeventargs e)
{
If (e. changetype = watcherchangetypes. created)
{
Oncreated (source, e );

}
Else if (e. changetype === watcherchangetypes. changed)
{
Onchanged (source, e );

}
Else if (e. changetype = watcherchangetypes. deleted)
{
Ondeleted (source, e );

}
}

Private static void oncreated (object source, filesystemeventargs e)
{

Console. writeline ("file creation event processing logic ");

}

Private static void onchanged (object source, filesystemeventargs e)
{

Console. writeline ("file change event processing logic ");
}

Private static void ondeleted (object source, filesystemeventargs e)
{

Console. writeline ("File Deletion event processing logic ");
}

Private static void onrenamed (object source, renamedeventargs e)
{

Console. writeline ("file rename event processing logic ");
}

}
}

Myfilesystemwather class:

Using system;
Using system. collections;
Using system. io;
Using system. threading;

Namespace test
{

Public delegate void completed (string key );

Public class myfilesystemwather
{
Private filesystemwatcher fswather;

Private hashtable hstbwather;

Public event renamedeventhandler onrenamed;
Public event filesystemeventhandler onchanged;
Public event filesystemeventhandler oncreated;
Public event filesystemeventhandler ondeleted;

/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "path"> path to be monitored </param>
Public myfilesystemwather (string path, string filter)
{
If (! Directory. exists (path ))
{
Throw new exception ("path not found:" + path );
}

Hstbwather = new hashtable ();

Fswather = new filesystemwatcher (path );
// Monitor sub-Directories
Fswather. includesubdirectories = false;
Fswather. filter = filter;
Fswather. renamed + = new renamedeventhandler (fswather_renamed );
Fswather. changed + = new filesystemeventhandler (fswather_changed );
Fswather. created + = new filesystemeventhandler (fswather_created );
Fswather. deleted + = new filesystemeventhandler (fswather_deleted );
}

/// <Summary>
/// Start monitoring
/// </Summary>
Public void start ()
{
Fswather. enableraisingevents = true;
}

/// <Summary>
/// Stop monitoring
/// </Summary>
Public void stop ()
{
Fswather. enableraisingevents = false;
}

/// <Summary>
/// Filesystemwatcher's Event Notification processing process
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Private void fswather_renamed (object sender, renamedeventargs e)
{
Lock (hstbwather)
{
Hstbwather. add (e. fullpath, e );
}

Watcherprocess = new watcherprocess (sender, e );
Watcherprocess. oncompleted + = new completed (watcherprocess_oncompleted );
Watcherprocess. onrenamed + = new renamedeventhandler (watcherprocess_onrenamed );
Thread = new thread (watcherprocess. process );
Thread. start ();
}

Private void watcherprocess_onrenamed (object sender, renamedeventargs e)
{
Onrenamed (sender, e );
}

Private void fswather_created (object sender, filesystemeventargs e)
{
Lock (hstbwather)
{
Hstbwather. add (e. fullpath, e );
}
Watcherprocess = new watcherprocess (sender, e );
Watcherprocess. oncompleted + = new completed (watcherprocess_oncompleted );
Watcherprocess. oncreated + = new filesystemeventhandler (watcherprocess_oncreated );
Thread threaddeal = new thread (watcherprocess. process );
Threaddeal. start ();
}

Private void watcherprocess_oncreated (object sender, filesystemeventargs e)
{
Oncreated (sender, e );
}

Private void fswather_deleted (object sender, filesystemeventargs e)
{
Lock (hstbwather)
{
Hstbwather. add (e. fullpath, e );
}
Watcherprocess = new watcherprocess (sender, e );
Watcherprocess. oncompleted + = new completed (watcherprocess_oncompleted );
Watcherprocess. ondeleted + = new filesystemeventhandler (watcherprocess_ondeleted );
Thread tddeal = new thread (watcherprocess. process );
Tddeal. start ();
}

Private void watcherprocess_ondeleted (object sender, filesystemeventargs e)
{
Ondeleted (sender, e );
}

Private void fswather_changed (object sender, filesystemeventargs e)
{
If (e. changetype = watcherchangetypes. changed)
{
If (hstbwather. containskey (e. fullpath ))
{
Watcherchangetypes oldtype = (filesystemeventargs) hstbwather [e. fullpath]). changetype;
If (oldtype = watcherchangetypes. created | oldtype = watcherchangetypes. changed)
{
Return;
}
}
}

Lock (hstbwather)
{
Hstbwather. add (e. fullpath, e );
}
Watcherprocess = new watcherprocess (sender, e );
Watcherprocess. oncompleted + = new completed (watcherprocess_oncompleted );
Watcherprocess. onchanged + = new filesystemeventhandler (watcherprocess_onchanged );
Thread = new thread (watcherprocess. process );
Thread. start ();
}

Private void watcherprocess_onchanged (object sender, filesystemeventargs e)
{
Onchanged (sender, e );
}

Public void watcherprocess_oncompleted (string key)
{
Lock (hstbwather)
{
Hstbwather. remove (key );
}
}
}
}

Analysis

Filesystemwatcher Basics

Attribute:

Path -- this attribute tells filesystemwatcher which path it needs to monitor. For example, if we set this attribute to "c: test", the object will monitor all changes (including deleting, modifying, creating, and renaming) to all files in the test directory ).

Includesubdirectories -- this attribute indicates whether the filesystemwatcher object should monitor changes in subdirectories (all files.

Filter -- this attribute allows you to filter out changes to some types of files. For example, if we only want to submit a notification when the txt file is modified, created, or deleted, we can set this attribute to "* txt ". This attribute is very convenient when processing high-traffic or large directories.

Policyfilter -- gets or sets the change type to be monitored. You can further filter the types of changes to be monitored, such as watcher. policyfilter = policyfilters. lastaccess | policyfilters. lastwrite

| Policyfilters. filename | policyfilters. directoryname;

Event:

Changed -- this event is submitted when a file in the monitored directory is modified. It is worth noting that this event may be submitted multiple times, even if only one change occurs to the file content. This is because other attributes of the file are also changed when the file is saved.

Created -- this event is submitted when a file is created in the monitored directory. If you plan to use this event to move a new event, you must write some error handling code in the event processor to handle the usage of the current file by other processes. This is because the created event may be submitted before the file creation process releases the file. If you are not prepared to correctly handle this situation, an exception may occur.

Deleted -- submit this event when a file in the monitored directory is deleted.

Renamed -- submit this event when a file in the monitored directory is renamed.

 

Note: If you do not set enableraisingevents to true, the system does not submit any event. If the filesystemwatcher object sometimes does not seem to work, check enableraisingevents first to make sure it is set to true.

 

Event Processing

 

When filesystemwatcher calls an event processor, it contains two independent variables: an object called "sender" and a filesystemeventargs object called "e. The independent variable we are interested in is the filesystemeventargs independent variable. This object contains the reason for submitting the event. The following are some attributes of the filesystemeventargs object:

 

Attribute:

 

Name -- name of the file in which the event is submitted. It does not contain the file path-it only contains the file or directory name submitted using the event.

Changetype -- this is a watcherchangetypes instance that specifies the type of event to be submitted. Valid values include:

Changed

Created

Deleted

Renamed

Fullpath -- this attribute contains the complete path of the file for the event to be submitted, including the file name and directory name.

 

Note: The filesystemeventargs object is an independent variable in the monitoring folder for file creation, deletion, and modification. If it is renamed to the renamedeventargs object, an oldfullpath is added in addition to the attribute value of the filesystemeventargs object, the name of the file before renaming.

 

The above is the basic knowledge of filesystemeventargs, most of which are searched online and sorted out by yourself.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.