1. Computing & Technology

Discuss in my forum

How to Check if a Given File Name is Valid Using Delphi

A custom IsFileNameValid Delphi function

By , About.com Guide

If you have an application that operates on the file system and one of the tasks of the application is creating or manipulating files, then you might need to check if a given file name is valid.

For example, if you're using the Windows Explorer to create a new file manually and you try to use the "pipe" (vertical bar) character "|", you will get an error:

A file name cannot contain any of the following characters: \ / : * ? " < > |

The solution to this is to make sure Windows will allow your code to save a file using the specified file name. This can be done with a custom Delphi function: IsValidFileName.

Is File Name Valid

The IsValidFileName validates a given file name to report if a string value represents a valid Windows file name.

The function will return false if the parameter "fileName" is an empty string or if it contains any of the invalid characters:

 //test if a "fileName" is a valid Windows file name
 //Delphi >= 2005 version
 function IsValidFileName(const fileName : string) : boolean;
 const
   InvalidCharacters : set of char = ['\', '/', ':', '*', '?', '"', '<', '>', '|'];
 var
   c : char;
 begin
   result := fileName <> '';
 
   if result then
   begin
     for c in fileName do
     begin
       result := NOT (c in InvalidCharacters) ;
       if NOT result then break;
     end;
   end;
 end; (* IsValidFileName *)
 
Note: "InvalidCharacters" is a set type constant.

If your Delphi version (<= Delphi 7) does not support the for in loop, use the next implementation of the IsValidFileName function:

 //test if a "fileName" is a valid Windows file name
 //Dellphi <= 7 version
 function IsValidFileName(const fileName : string) : boolean;
 const
   InvalidCharacters : set of char = ['\', '/', ':', '*', '?', '"', '<', '>', '|'];
 var
   cnt : integer;
 begin
   result := fileName <> '';
 
   if result then
   begin
     for cnt := 1 to Length(fileName) do
     begin
       result := NOT (fileName[cnt] in InvalidCharacters) ;
       if NOT result then break;
     end;
   end;
 end; (* IsValidFileName *)
 

Delphi tips navigator:
» Running Delphi Application on Startup on Vista - Create Manifest for UAC if Not Running Under Administrative Rights
« Is Computer Joined to a Domain - Programmatically Check using Delphi

©2012 About.com. All rights reserved.

A part of The New York Times Company.