2009. július 18., szombat

Strip illegal characters from a file name


Problem/Question/Abstract:

I am attempting to create a file from a title of a webpage. The title can contain illegal filename characters such as \ / : ? etc. What is the best way to filter out these characters? I want to remove them entirely, and not replace them with a space. Thus, I would like to keep alphanumeric, dashes, underscores, space, and a few other special characters only.

Answer:

Solve 1:

Something like the function below would do. In my code, the function replaces dodgy chars with a replacement, but I guess it would still work if you specificed the 'CunfriendlyReplacement' as an empty string.

{ ... }
const
{$IFDEF WIN32}
  CpathDelimiter = '\';
{$ELSE}
  CpathDelimiter = '/';
{$ENDIF}
  CdelimiterChar = '_';
  CunfriendlyChars = [CpathDelimiter, '.', ':', CdelimiterChar, '/', '<', '>', '|'];
  CunfriendlyReplacement = '-';
  { ... }

function makeNameFileFriendly(const inName: string): string;
var
  charIndex: Integer;
  thisChar: Char;
begin
  result := '';
  for charIndex := 1 to length(inName) do
  begin
    thisChar := inName[charIndex];
    if (thisChar in CunfriendlyChars) then
      result := result + CunfriendlyReplacement
    else
      result := result + thisChar;
  end;
end;


Solve 2:

function ValidateFilename(Filename: WideString): WideString;
var
  i: Integer;
begin
  Result := '';
  for i := 1 to Length(Filename) do
  begin
    if Pos(Filename[i], WideString('\/:*?<>|,' + #34)) = 0 then
      Result := Result + Filename[i];
  end;
  Result := Trim(Result);
end;

Nincsenek megjegyzések:

Megjegyzés küldése