Given a file system path, is there a way to obtain the short path name on Windows within Mathematica?

E.g. C:\Program Files should transform to C:\PROGRA~1 (or similar, depending on the system).

Motivation: Work around problems that occur when non-ASCII characters are present in paths.

| improve this question | | | | |

Windows Command Line

Here is a way using the Windows command line:

getShortPathName[path_] :=
  Import["!for %p in (\""~~path~~"\") do @echo %~sp", "Text"]

So then:


(* "C:\\PROGRA~1\\WOLFRA~1\\MATHEM~1\\11.2" *)


Here is a way using NETLink...

First, we declare the Win32 API function GetShortPathName:


getShortPathNameWin32 =
  DefineDLLFunction @
  "[DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]
   public static extern int GetShortPathName(
       [MarshalAs(UnmanagedType.LPTStr)] string path,
       [MarshalAs(UnmanagedType.LPTStr)] System.Text.StringBuilder shortPath,
       int shortPathLength

Next, we define our own function that performs the necessary ceremony to invoke that API function:

$maxPathLength = 260;

getShortPathName[path_] :=
  NETBlock @ Module[{shortPath = NETNew["System.Text.StringBuilder", $maxPathLength]}
  , getShortPathNameWin32[path, shortPath, $maxPathLength]
  ; shortPath@ToString[]

So then:


(* "C:\\PROGRA~1\\WOLFRA~1\\MATHEM~1\\11.2" *)
| improve this answer | | | | |
  • $\begingroup$ Crazy....man... $\endgroup$ – yode Nov 17 '17 at 15:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.