Is FileSystemWatcher on Windows currently broken?

I’ve been trying to figure out why this code won’t work… specifically… no ‘renamed’ events are showing up… although the other three events seem to be working fine… is the RenamedEventHandler just not working, or am I missing something obvious here?

using UnityEngine;
using System.Collections;
using System.IO;
     
public class FileWatcher : MonoBehaviour
{
	public string fileToWatch = "*.*";
	private FileSystemWatcher watcher;
       
	
	IEnumerator  Start ()
	{
		watcher = new FileSystemWatcher ();
		watcher.Path = Application.streamingAssetsPath;
		watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.DirectoryName 
				| NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite 
				| NotifyFilters.Size;
		watcher.Filter = fileToWatch;
		watcher.Renamed += new RenamedEventHandler (OnRenamed);
		watcher.Changed += new FileSystemEventHandler (OnChanged);
		watcher.Created += new FileSystemEventHandler (OnChanged);
		watcher.Deleted += new FileSystemEventHandler (OnChanged);
		watcher.Error += new ErrorEventHandler(OnError);
		
		watcher.IncludeSubdirectories = true;
		watcher.EnableRaisingEvents = true;

		yield return null;
	}
	
	private void OnChanged (object source, FileSystemEventArgs e)
	{
		WatcherChangeTypes wct = e.ChangeType;
		Debug.Log (e.FullPath + ": " + wct.ToString ());
	}
	
	private void OnRenamed (object source, RenamedEventArgs e)
	{
		WatcherChangeTypes wct = e.ChangeType;
		Debug.Log ("file " + e.OldFullPath + " renamed to " + e.FullPath + ": " + wct.ToString ());
	}
	
	private void OnError(object source, ErrorEventArgs e)
	{
		Debug.Log("Error detected: " + e.GetException().GetType().ToString());
	}
}

I think Unity just doesn’t “Rename” files, but rather deletes and creates new ones. At least in my test case (very similar to yours) I see both come up but rename never does.

1 Like

Answer below

I know, old thread but…can anyone confirm that this code still works? I’m trying to get the FileSystemWatcher to monitor my Levels folder for changes and auto-load the files, but I’m not receiving any callbacks at my handlers. I have tested from within the editor in play mode, as an edit-time editor script and in the runtime build, but the events are never fired even though I’m renaming and changing files and directories.

Answering my own question:

I forgot that this is a threaded operation and Unity might behave unexpectedly. Using the Unity API actually caused an exception but because it was wrapped in a Debug.LogFormat statement, it didn’t show in the console output, for whatever reason. Might be a bug, I can test it some more, but the callbacks were actually working just not showing in the console when also calling Unity code. But just like the thread starter I’m not getting renamed events, only deleted when renaming a file or directory.