currentfilename = fullfile(d, imagefiles(k).name);
The .name field returned by dir() never includes folder information: it is the basic file name (including extension) only.
Since R2015b or so, there is also a .folder field, so
currentfilename = fullfile(imagefiles(k).folder, imagefiles(k).name);
could be used. That is useful if you used wildcards in folder specifications.
I find it easier to attach the folder names before-hand:
filenames = fullfile(d, {imagefiles.name});
and then extract filenames{k} and use that.