Several scenarios for using file monitoring object FileSystemWatcher in C #

Source: Internet
Author: User

A recent requirement in a project is to get real-time access to content in a text file that is not regularly changed. The first thought is to use the program to access this file regularly, because the real-time requirements are high, the interval can not exceed 1S, and every time the text content to be distributed to the Web server to do other operations, and that text is sometimes frequently, 1 seconds may be many times, But it is also possible that there will be no writing for quite a long period of time.

In this way, if every second to access the file, one is the IO problem, and each operation will cause the back end of a series of programs, text in a long time without writing, a second trigger a series of futile things too undesirable.

Finally discovered the FileSystemWatcher object in C #, before applying FileSystemWatcher, first understand the basic properties and events of this object, first popularize FileSystemWatcher basic knowledge.

FileSystemWatcher Foundation

Property:

path--This property tells FileSystemWatcher which path it needs to monitor. For example, if we set this property to "C:\test", the object monitors all changes (including deletion, modification, creation, renaming) of all files in the test directory.

includesubdirectories--This property indicates whether the FileSystemWatcher object should monitor changes in subdirectories (all files).

filter--This property allows you to filter out changes in certain types of files. For example, if we only want to submit a notification when the TXT file is modified/new/deleted, you can set this property to "*txt". This property is handy when working with high-traffic or large catalogs.

notifyfilter--Gets or sets the type of change to monitor. You can further filter the types of changes you want to monitor, such as watcher. NotifyFilter = Notifyfilters.lastaccess | Notifyfilters.lastwrite

| Notifyfilters.filename | Notifyfilters.directoryname;

Event:

changed--This event is submitted when a file in the directory being monitored is modified. It is important to note that this event may be submitted multiple times, even if the contents of the file only have a change. This is because other properties of the file have changed when the file is saved.

created--This event is submitted when a new file is created in the monitored directory. If you plan to use this event to move the newly created event, you must write some error handling code in the event handler that can handle the situation where the current file is being used by another process. This is done because the created event may be committed before the file-creation process releases the file. If you do not have the code to handle this situation correctly, you may get an exception.

deleted--when a file in the monitored directory is deleted, the event is submitted.

renamed--when a file in the monitored directory is renamed, the event is submitted.

Note: If you do not set EnableRaisingEvents to True, the system will not commit any one event. If sometimes FileSystemWatcher objects do not seem to work, check enableraisingevents first to make sure it is set to true.

Event handling
When FileSystemWatcher invokes an event handler, it contains two arguments-an object called "sender" and a FileSystemEventArgs object called "E". The arguments we are interested in are filesystemeventargs arguments. This object contains the cause of the commit event. The following are some of the properties of the FileSystemEventArgs object:

Property:
name--the name of the file that causes the event to be committed in this attribute. It does not contain the path to the file-it contains only the file or directory name that was committed using the event.

changetype--This is a watcherchangetypes that indicates which type of event to commit. The valid values are:

Changed

Created

Deleted

Renamed

fullpath--This property contains the full path of the file that causes the event to be committed, including the filename and directory name.

Note: The FileSystemEventArgs object is an argument under the Monitoring folder when the file is created, deleted, modified, and if it is renamed the RenamedEventArgs object at this time except for the FileSystemEventArgs object's property value, One more Oldfullpath, the name of the file before renaming.

The above is the basic knowledge of FileSystemEventArgs, most of the search from the Internet and then a little tidying up a bit.

Here's a simple usage:
Using System;

Using System.IO;

03

Namespace test

05 {

Class Program

07 {

static void Main (string[] args)

09 {

10

11

Watcherstrat (@ "C:\test", "*.txt");

13//Because it is a console program, add an input to avoid the main thread execution, the monitoring effect can not be seen

Console.readkey ();

15

16}

17

18

19

private static void Watcherstrat (string path, String filter)

21 {

FileSystemWatcher watcher = new FileSystemWatcher ();

Watcher. Path = path;

24

Watcher. Filter = filter;

26

Watcher. Changed + = new FileSystemEventHandler (onprocess);

Watcher. Created + = new FileSystemEventHandler (onprocess);

Watcher. Deleted + = new FileSystemEventHandler (onprocess);

Watcher. Renamed + = new Renamedeventhandler (onrenamed);

31

Watcher. EnableRaisingEvents = true;

33}

34

35

36

37

$ private static void Onprocess (object source, FileSystemEventArgs e)

39 {

if (e.ChangeType = = watcherchangetypes.created)

41 {

oncreated (source, E);

43

44}

if (e.ChangeType = = watcherchangetypes.changed)

46 {

OnChanged (source, E);

48

49}

-else if (e.ChangeType = = watcherchangetypes.deleted)

51 {

ondeleted (source, E);

53

54}

55}

56

oncreated private static void (object source, FileSystemEventArgs e)

58 {

59

Console.WriteLine ("File New event processing logic");

61

62}

63

+ private static void OnChanged (object source, FileSystemEventArgs e)

65 {

66

Console.WriteLine ("File Change event handling logic");

68}

69

+ private static void Ondeleted (object source, FileSystemEventArgs e)

71 {

72

Console.WriteLine ("File Delete event processing logic");

74}

75

private static void Onrenamed (object source, RenamedEventArgs e)

77 {

78

Console.WriteLine ("File renaming event processing logic");

80}

81

82}

83}

Using the above method, the OnChanged event will be triggered two times at a time when the text file changes, because there are other attributes of the file that change, such as the modification time, in addition to the text content changes.

In order to solve this problem, it is also convenient for the actual use of the project, wrote the following several classes to actually use:


Main method:
Using System;

Using System.IO;

03

Namespace test

05 {

Class Program

07 {

static void Main (string[] args)

09 {

10

11

12

Myfilesystemwather mywather = new Myfilesystemwather (@ "C:\test", "*.txt");

Mywather.onchanged + = new FileSystemEventHandler (OnChanged);

mywather.oncreated + = new FileSystemEventHandler (oncreated);

Mywather.onrenamed + = new Renamedeventhandler (onrenamed);

mywather.ondeleted + = new FileSystemEventHandler (ondeleted);

Mywather.start ();

19//Because it is a console program, add an input to avoid the main thread execution, the monitoring effect can not be seen

Console.readkey ();

21st

22}

23

private static void Oncreated (object source, FileSystemEventArgs e)

25 {

26

Console.WriteLine ("File New event processing logic");

28

29}

30

-Private static void OnChanged (object source, FileSystemEventArgs e)

32 {

33

Console.WriteLine ("File Change event processing logic");

35}

36

PNS private static void Ondeleted (object source, FileSystemEventArgs e)

38 {

39

Console.WriteLine ("File Delete event processing logic");

41}

42

$ private static void Onrenamed (object source, RenamedEventArgs e)

44 {

45

Console.WriteLine ("File Rename event processing logic");

47}

48

49}

50}

Watcherprocess class:
Using System.IO;

02

Namespace test

04 {

public class Watcherprocess

06 {

The private object sender;

The private object Eparam;

09

Ten public event Renamedeventhandler onrenamed;

public event FileSystemEventHandler OnChanged;

public event FileSystemEventHandler oncreated;

public event FileSystemEventHandler ondeleted;

public event completed oncompleted;

15

Public Watcherprocess (object sender, Object Eparam)

17 {

This.sender = sender;

This.eparam = Eparam;

20}

21st

public void Process ()

23 {

if (eparam.gettype () = = typeof (RenamedEventArgs))

25 {

Onrenamed (sender, (RenamedEventArgs) eparam);

OnCompleted (((RenamedEventArgs) eparam). FullPath);

28}

Else

30 {

FileSystemEventArgs e = (FileSystemEventArgs) Eparam;

if (e.ChangeType = = watcherchangetypes.created)

33 {

Oncreated (sender, E);

OnCompleted (E.fullpath);

36}

PNS else if (e.ChangeType = = watcherchangetypes.changed)

38 {

OnChanged (sender, E);

OnCompleted (E.fullpath);

41}

if (e.ChangeType = = watcherchangetypes.deleted)

43 {

Ondeleted (sender, E);

OnCompleted (E.fullpath);

46}

+ Else

48 {

OnCompleted (E.fullpath);

50}

51}

52}

53}

54}

Myfilesystemwather class:
001 using System;

002 using System.Collections;

003 using System.IO;

004 using System.Threading;

005

006 Namespace Test

007 {

008

009 public delegate void completed (string key);

010

011 public class Myfilesystemwather

012 {

013 private FileSystemWatcher Fswather;

014

015 Private Hashtable Hstbwather;

016

017 public event Renamedeventhandler onrenamed;

018 public event FileSystemEventHandler OnChanged;

019 public event FileSystemEventHandler oncreated;

020 public event FileSystemEventHandler ondeleted;

021

022//<summary>

023///constructor

024//</summary>

025//<param name= "path" > Path to monitor </param>

026 public Myfilesystemwather (string path, String filter)

027 {

028 if (! Directory.Exists (PATH))

029 {

030 throw new Exception ("Path not found:" + path);

031}

032

033 Hstbwather = new Hashtable ();

034

035 Fswather = new FileSystemWatcher (path);

036//Whether to monitor sub-directories

037 fswather.includesubdirectories = false;

038 fswather.filter = Filter;

039 fswather.renamed + = new Renamedeventhandler (fswather_renamed);

040 fswather.changed + = new FileSystemEventHandler (fswather_changed);

041 fswather.created + = new FileSystemEventHandler (fswather_created);

042 fswather.deleted + = new FileSystemEventHandler (fswather_deleted);

043}

044

045//<summary>

046//Start monitoring

047//</summary>

048 public void Start ()

049 {

050 fswather.enableraisingevents = true;

051}

052

053//<summary>

054///Stop monitoring

055//</summary>

056 public void Stop ()

057 {

058 fswather.enableraisingevents = false;

059}

060

061//<summary>

062///FilesystemWatcher The event notification process itself

063//</summary>

064//<param name= "Sender" ></param>

065//<param name= "E" ></param>

066 private void Fswather_renamed (object sender, RenamedEventArgs e)

067 {

068 Lock (Hstbwather)

069 {

070 Hstbwather.add (E.fullpath, E);

071}

072

073 watcherprocess watcherprocess = new Watcherprocess (sender, E);

074 watcherprocess.oncompleted + = new completed (watcherprocess_oncompleted);

075 watcherprocess.onrenamed + = new Renamedeventhandler (watcherprocess_onrenamed);

076 thread thread = new Thread (watcherprocess.process);

077 Thread. Start ();

078}

079

080 private void Watcherprocess_onrenamed (object sender, RenamedEventArgs e)

081 {

082 onrenamed (sender, E);

083}

084

085 private void Fswather_created (object sender, FileSystemEventArgs e)

086 {

087 Lock (Hstbwather)

088 {

089 Hstbwather.add (E.fullpath, E);

090}

091 watcherprocess watcherprocess = new Watcherprocess (sender, E);

092 watcherprocess.oncompleted + = new completed (watcherprocess_oncompleted);

093 watcherprocess.oncreated + = new FileSystemEventHandler (watcherprocess_oncreated);

094 thread threaddeal = new Thread (watcherprocess.process);

095 Threaddeal.start ();

096}

097

098 private void Watcherprocess_oncreated (object sender, FileSystemEventArgs e)

099 {

Oncreated (sender, E);

101}

102

103 private void Fswather_deleted (object sender, FileSystemEventArgs e)

104 {

Hstbwather Lock (a)

106 {

107 Hstbwather.add (E.fullpath, E);

108}

109 watcherprocess watcherprocess = new Watcherprocess (sender, E);

watcherprocess.oncompleted + = new completed (watcherprocess_oncompleted);

111 watcherprocess.ondeleted + = new FileSystemEventHandler (watcherprocess_ondeleted);

The tddeal thread = new Thread (watcherprocess.process);

113 Tddeal.start ();

114}

115

watcherprocess_ondeleted private void (object sender, FileSystemEventArgs e)

117 {

118 ondeleted (sender, E);

119}

120

121 private void Fswather_changed (object sender, FileSystemEventArgs e)

122 {

123 if (e.ChangeType = = watcherchangetypes.changed)

124 {

if (Hstbwather.containskey (E.fullpath))

126 {

127 WatcherChangeTypes Oldtype = ((FileSystemEventArgs) Hstbwather[e.fullpath]). changetype;

if (Oldtype = = Watcherchangetypes.created | | oldtype = = watcherchangetypes.changed)

129 {

The return of the;

131}

132}

133}

134

135 Lock (Hstbwather)

136 {

137 Hstbwather.add (E.fullpath, E);

138}

139 Watcherprocess watcherprocess = new Watcherprocess (sender, E);

watcherprocess.oncompleted + = new completed (watcherprocess_oncompleted);

141 watcherprocess.onchanged + = new FileSystemEventHandler (watcherprocess_onchanged);

142 Thread thread = new Thread (watcherprocess.process);

143 Thread. Start ();

144}

145

146 private void Watcherprocess_onchanged (object sender, FileSystemEventArgs e)

147 {

148 OnChanged (sender, E);

149}

150

151 public void watcherprocess_oncompleted (string key)

152 {

153 Lock (Hstbwather)

154 {

155 Hstbwather.remove (key);

156}

157}

158}

159}


A thread-safe hashtable is used to handle a change that triggers two events, and it is important to note that in real-world projects, when a thread is watcherprocess to handle its business logic when it is triggered by a monitoring file, Whether the business logic succeeds or fails (for example, if an exception is thrown, try it) make sure that Watcherprocess's completed is Myfilesystemwather's Watcherprocess_ OnCompleted executes the Hashtable key to remove the corresponding change file, or the next time the file changes it will not trigger your business logic.

There is the file monitoring, when the monitored files are written, there will be I/O conflict, Even if the write file is FileShare.Read will appear, to really solve the seemingly only filemaping method, but my project text writing software is not we can control, so only to deal with the exception of the method to solve.

Several scenarios for using file monitoring object FileSystemWatcher in C #

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.