The issue is that, as the comments in the code say, you have to keep changeListener
alive.
That is, keep a reference somewhere where it is not destroyed.
In the with-figures version a reference is probably kept in the workspace of the nested functions (yet another reason not to use them).
The following works for me:
function listeners = FileWatch(pathToWatch, callback)
persistent Listeners;
% to check/clear the existing ones:
listeners = [];
switch pathToWatch
case 'clear'
Listeners = [];
return
case 'list'
listeners = Listeners;
return;
end
fileObj = System.IO.FileSystemWatcher(pathToWatch);
fileObj.EnableRaisingEvents = true;
changeListener = addlistener(fileObj, 'Changed', @onChange); %need to keep in scope
% alternatively:
% taking the callback as input-argument would make it a more universal function:
% changeListener = addlistener(fileObj, 'Changed', callback);
if isempty(Listeners)
Listeners = changeListener;
else
Listeners(end+1) = changeListener;
end
end
function onChange(~,evt)
newestfile = char(evt.FullPath.ToString());
fprintf('File-Event: %s\n', newestfile);
% do whatever you want to do with it :)
end %onChange