如何解决如何将 ' 字符添加到 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','');
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]);
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;
但是对于以下行:
'这是一个 \= 测试'='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',''));
if Str <> Str1 then
Application.MessageBox('Different value','Error');
finally
IniFile.Free;
end;
end;
当然,您也可以转义其他字符,例如 CR 和 LF 等控制字符。你有这个想法:-)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。