Welcome to Marlon's place!


Message of the day


"There is a brave man waiting, who'll take me back to where I come from"


(The Black Heart Rebellion)

How to check if a filename is valid

posted: April 5, 2009

If your application needs to read from or write to files, and you let your users specify the filename, you'd better make sure the suggested filename is valid.

Fortunately, doing so is very easy - this article will show you how to do it for the Windows platform.

Basically, there's a set of characters that is not allowed for usage in a filename. If you do try to enter one of these characters, for example if you want to rename a file using the Windows Explorer, you'll get an error stating that the filename cannot contain this or that character.

Since we know which characters aren't allowed, we now know what to check for. So let's move on to the function:

function IsValidWindowsFileName(const fileName : string) : boolean;
const
  invalidChars : set of char = ['\', '/', ':', '*', '?', '"', '<', '>', '|'];
var
  idx : integer;
begin
  result := filename <> '';

  if result then
  begin
    idx := 1;
    while (idx <= Length(filename)) and result do
    begin
      result := NOT (fileName[idx] in invalidChars) ;
      Inc(idx);
    end;
  end;
end;

Because of the while loop, checking the result each iteration, this function will stop as soon as it finds a character that is considered invalid.

If the end of the string is reached without finding an invalid character, the filename is valid - it's as simple as that.

Previous articles

Recent C++ stuff

Recent Delphi stuff

Recent Java stuff