October 01, 2008

Tips 1


How to Check if a Given File Name is Valid Using Delphi
A custom IsFileNameValid Delphi function


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 *)

0 comments:

Post a Comment

 

Copyright 2008 All Rights Reserved | Blogger Template by Computer Science and Computer Tips