Search code examples
matlabfilenamesfilepath

Alternative to command line for short path names


There is a specific case where having "path with space" doesn't work and I need to get the Windows short path names (e.g. Program Files = Progra~1 and Program Files (x86) = Progra~2).

Here what I'm doing for now :

[status, PATHROOT] = dos([ ...
    'for %A in ("' ...
    myPathWithSpace ...
    '") do @echo %~sA' ...
    ]);

Now, I tried using regexp and regexprep to format the file path, but it fails in some case to reproduce the dos short names. So how can I reproduce the dos command with MATLAB commands?

And here my ugly try with regexp and regexprep:

PATHROOT = regexprep(regexprep(regexp(myPathWithSpace,'\w:\\\w*\s\w*\\.*','match'),'\s', ''),'(\w:\\\w{6})\w*','$1~1');

Solution

  • Use this function:

    function shortPath = getshortpath(longPath)

    fs = actxserver('Scripting.FileSystemObject');

    shortPath = fs.GetFolder(longPath).ShortPath;

    fs.delete;