【发布时间】:2021-04-21 03:33:05
【问题描述】:
我正在使用 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;
但是对于以下行:
'这是一个 \= 测试'='我的 Tset'
ReadString 只会读取 'This is a \=' 作为键,而不是 'This is a \= Test'
【问题讨论】:
-
你的代码没有使用
'。你确定写作有问题吗?根据GetPrivateProfileString(),当值“用单引号或双引号括起来时,标记被丢弃” - 读取应该是问题,嗯? -
尝试改用
TMemIniFile。它可以解决TIniFile的各种缺点。 -
@RemyLebeau,抱歉,我尝试使用 TMemIniFile,但它无法解决我的问题。
-
Str := '"This is a "test" value"';是无效字符串,因为它是不正确的标点符号。它包含两个字符串("This is a "和" value"),孤立词test出现在引号之外。引号的规则是,如果短语在两个双引号之间,嵌入的引号应该是单引号(例如,“这是一个'测试'值”),如果外引号是单引号,那么内引号应该是双倍(例如,'This is a "test" value')。