Mega Code Archive

 
Categories / Delphi / Examples
 

Test if a string is a valid file name

The following code tests a given string for forbidden characters. The forbidden characters are dependent on whether it is a 8.3 (short) or a long file name. Thanks to a comment to A. Pottjeweid, who pointed out that the forward slash is a problem character as well. const { for short 8.3 file names } ShortForbiddenChars : set of Char = [';', '=', '+', '<', '>', '|', '"', '[', ']', '\', '/', '''']; { for long file names } LongForbiddenChars : set of Char = ['<', '>', '|', '"', '\', '/']; function TestFilename(Filename: String; islong: Boolean) : Boolean; var I: integer; begin Result := Filename <> ''; if islong then begin for I := 1 to Length(Filename) do Result := Result and not (Filename[I] in LongForbiddenChars); end else begin for I := 1 to Length(Filename) do Result := Result and not (Filename[I] in ShortForbiddenChars); end; end;