如何将 ' 字符添加到 TIniFile 中的键和值

How to add ' character to the key and values in TIniFile

我正在使用 Delphi XE3。我使用 TIniFile 写入 .ini 文件。问题之一是当我使用 WriteString() 将字符串写入 ini 文件时。虽然原始字符串中包含 ',但 TIniFile 写入 ini 文件后会将其删除。更糟糕的是,当字符串同时包含 '".

见下文:

procedure TForm1.Button4Click(Sender: TObject);
var
  Str, Str1: string;
  IniFile: TIniFile;
begin
  IniFile := TIniFile.Create('E:\Temp\Test.ini');

  Str := '"This is a "test" value"';
  IniFile.WriteString('Test', 'Key', Str);
  Str1 := IniFile.ReadString('Test', 'Key', '');

  if Str <> Str1 then
    Application.MessageBox('Different value', 'Error');

  IniFile.Free;
end;

有没有办法确保 TIniFile 将围绕值写入 '

更新

我尝试转义和取消转义引号 ",以及我的 ini 文件中的 =,如下所示:

function EscapeQuotes(const S: String) : String;
begin
    Result := StringReplace(S, '\', '\', [rfReplaceAll]);
    Result := StringReplace(Result, '"', '\"', [rfReplaceAll]);
    Result := StringReplace(Result, '=', '\=', [rfReplaceAll]);
end;

function UnEscapeQuotes(const S: String) : String;
var
    I : Integer;
begin
    Result := '';
    I := 1;
    while I <= Length(S) do begin
        if (S[I] <> '\') or (I = Length(S)) then
            Result := Result + S[I]
        else begin
            Inc(I);
            case S[I] of
            '"': Result := Result + '"';
            '=': Result := Result + '=';
            '\': Result := Result + '\';
            else Result := Result + '\' + S[I];
            end;
        end;
        Inc(I);
    end;
end;

但对于以下行:

'This is a \= Test'='My Tset'

ReadString 只会读取 'This is a \=' 作为键,而不是 'This is a \= Test'

您不能在 INI 文件中写入任何内容。但是您可以转义任何不允许或以特殊方式处理的字符 Windows.

下面的简单代码实现了一个基本的转义机制(可以优化):

function EscapeQuotes(const S: String) : String;
begin
    Result := StringReplace(S, '\', '\', [rfReplaceAll]);
    Result := StringReplace(Result, '"', '\"', [rfReplaceAll]);
end;

function UnEscapeQuotes(const S: String) : String;
var
    I : Integer;
begin
    Result := '';
    I := 1;
    while I <= Length(S) do begin
        if (S[I] <> '\') or (I = Length(S)) then
            Result := Result + S[I]
        else begin
            Inc(I);
            case S[I] of
            '"': Result := Result + '"';
            '\': Result := Result + '\';
            else Result := Result + '\' + S[I];
            end;
        end;
        Inc(I);
    end;
end;

这样使用:

procedure Form1.Button4Click(Sender: TObject);
var
  Str, Str1: string;
  IniFile: TIniFile;
begin

  IniFile := TIniFile.Create('E:\Temp\Test.ini');
  try

    Str := '"This is a "test" for key=value"';
    IniFile.WriteString('Test', 'Key', EscapeQuotes(Str));
    Str1 := UnEscapeQuotes(IniFile.ReadString('Test', 'Key', ''));

    if Str <> Str1 then
      Application.MessageBox('Different value', 'Error');

  finally
    IniFile.Free;
  end;

end;

当然你也可以转义其他字符,例如CR和LF这样的控制字符。你有想法:-)