Andy Pemberton Rotating Header Image

Windows Short File Name (ShortPath) in ANT

I ran into an interesting problem today while working on an ANT build script. I needed to access the path of a directory in windows with spaces, but without using quotes. One way to do this is with the Windows short file name.

So, I needed to access the Windows short file name (also known as ShortPath) of a given directory in an ANT script. You know the ShortPath; it looks something like: C:\Docume~1\ for the directory: C:\Documents and Settings\

Because I needed to pass in the directory path to an IBM-specific script, I couldn’t have any quotes in the directory path (ie: their script was already using single and double quotes). After Googling around a bit, I found one or two ways to access the ShortPath, but no clear way to integrate this into my ANT build.

So, here it is:


...
<exec executable="cmd" dir="${basedir}" outputproperty="basedir.win.name">
    <arg line="/c command.com /c cd" />
</exec>
...

This call will take the base directory from your ANT project and use the command.com dos command to get the ShortPath of the file name. The command.com is a dos shell that exists on Windows XP and newer versions for backward compatibility and it ’speaks’ Windows ShortPaths.

So, tying it all together in an ANT target:


<target name="convertbasedir">
    <if>
        <os family="windows" />
        <then>
            <exec executable="cmd" dir="${basedir}" outputproperty="basedir.win.name">
                <arg line="/c command.com /c cd" />
            </exec>
            <path location="${basedir.win.name}" id="thepath" />
            <pathconvert property="basedir.name" targetos="unix" refid="thepath" />
        </then>
        <else>
            <property name="basedir.name" value="${basedir}" />
        </else>
    </if>
</target>

This target will store a cross-OS friendly property of the ANT project basedir in the property ${basedir.name} (note that I’m using the ant-contrib if/else tags for convenience).

Enjoy!

2 Comments on “Windows Short File Name (ShortPath) in ANT”

  1. #1 Mike
    on Jan 14th, 2009 at 9:34 pm

    It’s a shame command has been removed from xp64. This would have been ideal but without it this seems impossible to accomplish easily from Ant.

  2. #2 Andy
    on Jan 15th, 2009 at 12:36 pm

    @Mike - yeah, agreed. This was kind of an easy win/hack. You could probably dive in and write a batch script to handle it. Though, I’ve only ever needed to do this once and it had to do with IBM oddities.

Leave a Comment