Checking the case of a filename on Windows

Windows generally uses a case-insensitive but not case-preserving file system.

When writing some code that is intended to be used on Linux as well as Windows, I wanted it to fail on Windows in the same cases that it would fail on Linux, and this meant detecting when the case of a filename differed from its canonical case on the file system.

I want to ask “is this file name correct in terms of case?”

I was working in Java, but I think this issue would be similar in other languages: it’s difficult to ask for the canonical case version of a file name when we currently have a filename with abitrary case.

The only solution I came up with was to list the contents of the parent directory and check whether my arbitrary filename is listed with the correct case in the results:

// CaseCheck.java

import java.util.Arrays;
import java.io.File;
import java.io.IOException;

class CaseCheck
{
    private static File parentFile( File f )
    {
        File ret = f.getParentFile();
        if ( ret == null )
        {
            ret = new File( "." );
        }
        return ret;
    }

    private static boolean existsAndCaseCorrect( String fileName )
    {
        File f = new File( fileName );
        return Arrays.asList( parentFile( f ).list() ).contains( f.getName() );
    }

    public static void main( String[] args ) throws IOException
    {
        System.out.println( existsAndCaseCorrect( args[0] ) );
    }
}

Checking it on its own source file:

javac CaseCheck.java && java CaseCheck cASEcheck.java
false

javac CaseCheck.java && java CaseCheck CaseCheck.java
true

It seems to work.

Note that this also returns false if the file doesn’t exist, and will throw an error if the file name specifies a parent directory that doesn’t exist.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.