我正在使用德尔菲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;但以下几行:
‘这是一个\=测试’=‘我的设备’
ReadString只会把“这是一个\=”作为关键,而不是“这是一个\=测试”
发布于 2021-01-16 09:43:52
您不能在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。你有这样的想法:-)
https://stackoverflow.com/questions/65747368
复制相似问题