A method for actively checking folder for new files?

19 views (last 30 days)
hello all:
I'm trying to implement code that, once compiled and run, would actively check a specified folder regularly (for example, every 5 seconds) to look for the newest file added, and then perform some task to it (an image processing function that I've written).
I found this example which is similar to what I'm doing , and does work somewhat - in that it is able to report back that that there aren't any new files made while checking every 5 seconds. I'm just using that "new files found" text output as a quick check that it's actually checking.
however, when I add a test file to the specified folder while it's running, the program does not report back that new files have been found. it reports "new files found" on the first text output when run, but not on the following 5-second readouts.
here's the code as it stands right now:
myFolder = 'C:\Users\Documents\image_detection\sample_images\10192016\';
dir_content = dir('myFolder');
filenames = {dir_content.name};
current_files = filenames;
while true
pause(5)
dir_content = dir;
filenames = {dir_content.name};
new_files = setdiff(filenames,current_files);
if ~isempty(new_files)
% deal with the new files
current_files = filenames;
fprintf('new files found\n')
else
fprintf('no new files\n')
end
end

Answers (1)

Jan
Jan on 1 Feb 2017
Edited: Jan on 1 Feb 2017
You need two small modifications:
myFolder = 'C:\Users\Documents\image_detection\sample_images\10192016\';
dir_content = dir(myFolder); % Without quotes, Not: dir('myFolder')
filenames = {dir_content.name};
current_files = filenames;
while true
pause(5)
dir_content = dir(myFolder); % Not: dir;
...
The code can be simplified:
myFolder = 'C:\Users\Documents\image_detection\sample_images\10192016\';
olddir = dir(myFolder);
while true
pause(5)
newdir = dir(myFolder);
if ~isqual(newdir, olddir)
fprintf('new files found\n');
olddir = newdir;
else
fprintf('no new files\n')
end
end
Think of using an active approach:
w = System.IO.FileSystemWatcher(myFolder);
w.NotifyFilter = System.IO.NotifyFilters.LastWrite;
addlistener(w, 'Changed', @(x,y) disp('Modified'));
w.EnableRaisingEvents = true;
But if you want to compile this: It seems like there is a problem.
  3 Comments
jcledfo2
jcledfo2 on 16 Dec 2017
Jan Simon, how would you use the active approach to initialize an m code and pass the filename when the new file is added to the folder?
jerome maire
jerome maire on 27 Nov 2018
There is a typo in your suggested simplified code: should use isequal rather than isqual:
(if ~isequal(newdir, olddir))

Sign in to comment.

Categories

Find more on File Operations in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!