How can I sanitize a string for use as a filename?

后端 未结 9 821
说谎
说谎 2020-12-23 22:56

I\'ve got a routine that converts a file into a different format and saves it. The original datafiles were numbered, but my routine gives the output a filename based on an

9条回答
  •  悲&欢浪女
    2020-12-23 23:23

    Check if string has invalid chars; solution from here:

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

    And, for strings returning False, you could do something simple like this for each invalid character:

    var
      before, after : string;
    
    begin
      before := 'i am a rogue file/name';
    
      after  := StringReplace(before, '/', '',
                          [rfReplaceAll, rfIgnoreCase]);
      ShowMessage('Before = '+before);
      ShowMessage('After  = '+after);
    end;
    
    // Before = i am a rogue file/name
    // After  = i am a rogue filename
    

提交回复
热议问题