Movefile "the system cannot find the path specified" (Windows OS)
18 次查看(过去 30 天)
显示 更早的评论
I'm writing a small file renaming function to reverse the order of a list of image files (code below). I've run into an error using movefile. I get the error "Error using movefile ... The system cannot find the path specified." on the first call of movefile.
Surprisingly, I found that if I change
[dirname '\' 'TEMP_' fnames{n1}]
to
['TEMP_' fnames{n1}]
in both movefile calls, it now works and no longer throws the error. However, this means the files are moved to the local directory and then back again, which is obviously pretty slow when working with files on a network!
I've got a feeling this is related to the path length limitations of Windows OS. I've spent some time trying to research workarounds for the path length limit, but haven't yet found anything comprehensive. If anyone has a link to good material on the subject please let me know.
function reverseImgStackDir()
% Select folder
dirname = uigetdir('C:\');
% Compile list of tif image files
fnames = dir([dirname '\*.tif']);
fnames = {fnames.name}';
% 1st pass - swap file names
for n1 = 1:length(fnames)
% Index working from the end backwards
n2 = length(fnames)+1 - n1;
% Temporarily rename file
movefile([dirname '\' fnames{n2}], [dirname '\' 'TEMP_' fnames{n1}])
end
% 2nd pass - remove temp qualifier
for n1 = 1:length(fnames)
% Temporarily rename file
movefile([dirname '\' 'TEMP_' fnames{n1}], [dirname '\' fnames{n1}])
end
2 个评论
Guillaume
2018-5-24
Would adding just 5 characters take you over the MAX_PATH limit (260 characters)? I would suspect that's not the issue. What's a typical dirname value / length?
采纳的回答
Guillaume
2018-5-24
In addition to Jan's suggestion of the FileExchange files, since you're on Windows you can also delegate the renaming to .Net:
prefix = ['\\?\', dirname, '\']; %\\?\ to enable paths longer than MAX_PATH
System.IO.File.Move([prefix, fnames{n2}], [prefix, 'TEMP_', fnames{n1}]);
更多回答(2 个)
Jan
2018-5-24
编辑:Jan
2018-5-24
If the length of the names matter, use https://www.mathworks.com/matlabcentral/fileexchange/28249-getfullpath, which inserts \\?\ in front of long names automatically.
In addition https://www.mathworks.com/matlabcentral/fileexchange/29569-filerename is much faster than movefile.
3 个评论
Ameer Hamza
2018-5-24
Instead of constructing the complete path yourself, try to using fullfile(). It will properly construct the path by taking care of which slash to use ( \ for windows and / for mac)
path = fullfile(dirname, ['TEMP_' fnames{n1}]);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Filename Construction 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!