RingDotNetfor Ring

Watching a folder

A program can wait until something happens in a folder — a file is created, changed, renamed or deleted — instead of looking at the folder again and again. This lesson uses FileSystemWatcher, with a second copy of the program that makes the changes.

What you will learn#

Programs that watch folders are everywhere: a build tool that starts when a file is saved, an editor that notices that a file was changed by another program, a program that processes the files that other programs drop into an inbox folder.

The program#

samples/UsingDotNet/tutorials/ch05_watch_folder.ring
# Watching a folder - FileSystemWatcher: waiting for files to be created, changed, renamed and deleted
#   ring ch05_watch_folder.ring            the parent: it watches a folder and starts a second copy of this program (the child) that changes it
#   ring ch05_watch_folder.ring --child    the child (the parent starts it, you do not)
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Diagnostics"
	"System.Threading.Tasks"
}

func main

	if find(sysargv,"--child") > 0
		child(sysargv[len(sysargv)])
		return
	ok

	# A FileSystemWatcher tells a program that something happened in a folder: a file was created, changed, renamed or deleted. A program
	# that shows the files of a folder, a build tool that starts when a source file is saved, or a program that waits for files to arrive
	# in a folder uses it, instead of looking at the folder again and again.

	# 1. A folder to watch. The name comes from the system (it is different each time), so the program prints only what is the same each time.
	oPath = new Path()
	cFolder = oPath.Combine([ oPath.GetTempPath(), "ringdotnet-watch-" + oPath.GetRandomFileName() ])
	oDirectory = new Directory()
	oDirectory.CreateDirectory(cFolder)
	? "1. a folder to watch was created"

	# 2. The watcher: the folder, and the file names that interest us ("*.txt"). IncludeSubdirectories = True would watch the folders below too.
	oWatcher = new FileSystemWatcher().@New([ :path = cFolder, :filter = "*.txt" ])
	oWatcher.IncludeSubdirectories = False
	? "2. watching: " + oWatcher.Filter + ", subfolders: no"

	# 3. Start the child. It waits a moment, and then it creates a file, writes into it, renames it and deletes it, with a pause
	#    between the steps.
	oInfo = new ProcessStartInfo().@New([ :fileName = exefilename(), :arguments = '"' + filename() + '" --child "' + cFolder + '"' ])
	oInfo.UseShellExecute = False
	oInfo.CreateNoWindow = True
	oChild = new Process().Start(oInfo)
	? "3. the child was started"

	# 4. Wait for the changes. WaitForChanged waits for the next change (or for the time limit, here 4 seconds) and returns what happened.
	#    A change that happens while the program is NOT waiting is not reported: this is why the child makes a pause between the steps.
	? nl + "4. what happened:"
	aSeen = []
	while True
		oResult = oWatcher.WaitForChanged([ :changeType = "All", :timeout = 4000 ])
		if oResult.TimedOut
			exit
		ok
		cLine = describe(oResult)
		# one write can raise a few "Changed" events: the same line is printed once
		if len(aSeen) = 0 or aSeen[len(aSeen)] != cLine
			? "   " + cLine
			aSeen + cLine
		ok
		if oResult.ChangeType = "Deleted"
			exit
		ok
	end
	oChild.WaitForExit(5000)

	# 5. Clean up
	oWatcher.Dispose()
	oDirectory.Delete([ :path = cFolder, :recursive = True ])
	? nl + "5. the folder was deleted; the child's exit code: " + oChild.ExitCode

# what a change tells: the kind of change and the name (a rename also has the old name)
func describe oResult

	cKind = "" + oResult.ChangeType
	if cKind = "Renamed"
		return "Renamed   " + oResult.OldName + " -> " + oResult.Name
	ok
	return padRight(cKind,10) + oResult.Name

func padRight cText,nWidth

	return cText + copy(" ",nWidth - len(cText))

# ---------------------------------------------------------------- the child
func child cFolder

	oFile = new File()
	pause(1000)
	oFile.WriteAllText([ :path = cFolder + "/note.txt", :contents = "first" ])
	pause(600)
	oFile.AppendAllText([ :path = cFolder + "/note.txt", :contents = " and more" ])
	pause(600)
	oFile.Move([ :sourceFileName = cFolder + "/note.txt", :destFileName = cFolder + "/done.txt" ])
	pause(600)
	oFile.WriteAllText([ :path = cFolder + "/ignored.log", :contents = "not a .txt file" ])    # the filter *.txt does not match: no event
	pause(600)
	oFile.Delete(cFolder + "/done.txt")

func pause nMilliseconds

	new Task().Delay(nMilliseconds).Wait(NULL)
Output
1. a folder to watch was created
2. watching: *.txt, subfolders: no
3. the child was started

4. what happened:
   Created   note.txt
   Changed   note.txt
   Renamed   note.txt -> done.txt
   Deleted   done.txt

5. the folder was deleted; the child's exit code: 0

How it works#

Two programs#

A watcher has nothing to report if nobody changes the folder, and the program that waits cannot change it at the same moment. So the program starts a second copy of itself with --child and the name of the folder. The child waits a second, then creates note.txt, appends to it, renames it to done.txt, writes a file that the filter does not match, and deletes done.txt, with a pause between the steps. The parent only watches.

The watcher#

new FileSystemWatcher().@New([ :path = cFolder, :filter = "*.txt" ]) watches one folder. The filter is a file name pattern: only the names that match it are reported (it has * and ?; the tutorial File patterns (globbing) shows richer patterns for your own code). IncludeSubdirectories = True watches the folders below as well. Each change is a kind (Created, Changed, Renamed, Deleted) and the name of the file; a rename also has the old name.

Waiting for a change#

WaitForChanged([ :changeType = "All", :timeout = 4000 ]) waits for the next change and returns an object with ChangeType, Name, OldName and TimedOut. After four seconds without a change TimedOut is true and the loop ends. The ignored.log file does not match the filter, so the parent sees nothing for it.

Note

A watcher reports only the changes that happen while the program waits for them. Between two calls of WaitForChanged a change is not reported, so this style fits a loop that does nothing else, and tests. A program with a window or a server can use the events of the watcher (Created, Changed, Deleted, Renamed), which .NET raises on its own threads; Ring code runs on the Ring thread only, so such a program uses a timer and looks at the folder (the tutorial Timers and progress).

One write, several events#

Saving a file can raise more than one Changed event (the content and the time are written separately). The program prints a line only when it differs from the last one. Real programs do the same, and often wait a little (a debounce) so that a big save counts as one change.

Clean up#

Dispose() ends the watching. The program deletes the folder it made with Directory.Delete([ :path = ..., :recursive = True ]).

What you learned#

Exercises#

  1. Remove the filter (*) and look at the extra event for ignored.log.
  2. Set IncludeSubdirectories = True and make the child write into a subfolder.
  3. Make a loop that copies each new .txt file of an inbox folder to an archive folder.
  4. Count the Changed events for one AppendAllText call.

Next#

A project: analyze a log file

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.