0 0 Votes

Delphi: Ini Files: Problems with Quotes

Question by Chematik | 06/01/2013 at 09:58

I am using Ini-Files in Delphi in order to store some settings of my program. The writing and reading of the file is working quite well, only with values containing quotation marks, it comes to some strange behaviour.

The problem affects both, double and single quotes (" and ') and the problem seems to appear only occasionally, logic is not apparent to me. My first idea was to double the quote, but that only works sometimes.

If that is important, here are a few code snippets of my program:

uses IniFiles;
...
 
procedure ...
var
  ini: TIniFile;
  str: string;
begin
  ini:=TIniFile.Create(filename);
 
  //writing
  ini.WriteString('Section', 'Identifier', 'Value');
 
  //reading
  str:=ini.ReadString('Section', 'Identifier', 'Default');
 
  ini.free;
end;

But I do not think, that this code causes the problems, since this code can be found on the internet in each INI-Tutorial. But how to solve the issue?

ReplyPositiveNegative

Stefan Trost

Show Profile | Message
Avatar
0Best Answer
0 Votes

The functions WriteString and ReadString used in your code are using the Windows API functions ReadPrivateProfileString and GetPrivateProfileString internally.

With these functions, the following have to be observed: If the string value is enclosed in single or double quotes, the function returns the string without the quotes. So, the value "string" is retrieved as string. If there is only one quotation mark in the value or the quotes are appearing in the middle, the function returns them as they are stored in the INI file. That explains the behavior, you have described.

The solution is as follows:

function DoubleQuotes(s: string): string;
var
  k: integer;
begin
  k:=length(s);
  if k>1 then begin
    if (s[1])='''') and (s[k]='''') then s:=''''+s+'''';
    if (s[1])='"') and (s[k]='"') then s:='"'+s+'"';
  end;
  result:=s;
end;
 
...
 
s = '"VALUE"';
ini.WriteString('Section','Identifier',DoubleQuotes(s));

So, before writing the string into the INI file, we check, whether there are quotes of the same type at the front or the rear of the string. If so, we double both. Otherwise, the string is kept as it is.
06/01/2013 at 19:56

ReplyPositive Negative
Reply

Related Topics

Delphi: Hide Files
Question | 2 Answers

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.