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

后端 未结 9 829
说谎
说谎 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:21

    For anyone else reading this and wanting to use PathCleanupSpec, I wrote this test routine which seems to work... there is a definate lack of examples on the 'net. You need to include ShlObj.pas (not sure when PathCleanupSpec was added but I tested this in Delphi 2010) You will also need to check for XP sp2 or higher

    procedure TMainForm.btnTestClick(Sender: TObject);
    var
      Path: array [0..MAX_PATH - 1] of WideChar;
      Filename: array[0..MAX_PATH - 1] of WideChar;
      ReturnValue: integer;
      DebugString: string;
    
    begin
      StringToWideChar('a*dodgy%\filename.$&^abc',FileName, MAX_PATH);
      StringToWideChar('C:\',Path, MAX_PATH);
      ReturnValue:= PathCleanupSpec(Path,Filename);
      DebugString:= ('Cleaned up filename:'+Filename+#13+#10);
      if (ReturnValue and $80000000)=$80000000 then
        DebugString:= DebugString+'Fatal result. The cleaned path is not a valid file name'+#13+#10;
      if (ReturnValue and $00000001)=$00000001 then
        DebugString:= DebugString+'Replaced one or more invalid characters'+#13+#10;
      if (ReturnValue and $00000002)=$00000002 then
        DebugString:= DebugString+'Removed one or more invalid characters'+#13+#10;
      if (ReturnValue and $00000004)=$00000004 then
        DebugString:= DebugString+'The returned path is truncated'+#13+#10;
      if (ReturnValue and $00000008)=$00000008 then
        DebugString:= DebugString+'The input path specified at pszDir is too long to allow the formation of a valid file name from pszSpec'+#13;
      ShowMessage(DebugString);
    end;
    

提交回复
热议问题