Recent

Author Topic: TStringlist.Items.LoadFromFile unicode ??  (Read 4826 times)

penpen

  • New Member
  • *
  • Posts: 23
TStringlist.Items.LoadFromFile unicode ??
« on: May 03, 2016, 08:42:41 pm »
Hi,
I want to use
Code: Pascal  [Select][+][-]
  1. TSTringlist.loadfromfile
toload an unicode file.
But its only showing "??" instead of the string.

Is it possible to use TStringlist to read unicode files ?

penpen

wp

  • Hero Member
  • *****
  • Posts: 11916
Re: TStringlist.Items.LoadFromFile unicode ??
« Reply #1 on: May 03, 2016, 10:29:36 pm »
You must convert the read string to utf8. Another complication is that the file may begin with a BOM (byte-order-marker) which confuses the standard TStringList. Therefore, it is best to read the file into a memory stream first, extract the total string and convert it to utf8 by one of the Lazarus string converters. Use GuessEncoding to determine whether the file has a BOM or not. Note that this works also for ANSI-encoded strings.

Code: Pascal  [Select][+][-]
  1. uses
  2.   lconvencoding;
  3.  
  4. procedure ReadFileToStringList(AFilename: String; List: TStringList);
  5. var
  6.   stream: TMemorystream;
  7.   s: String;
  8. begin
  9.   stream := TMemoryStream.Create;
  10.   try
  11.     // Load file to memory stream
  12.     stream.LoadFromFile(AFileName);
  13.     // Put file content into a string variable
  14.     SetLength(s, stream.Size);
  15.     stream.ReadBuffer(s[1], stream.Size);
  16.     // Convert string to utf8 and assign it to stringlist
  17.     AStringList.Text := ConvertEncoding(s, GuessEncoding(s), EncodingUTF8);
  18.   finally
  19.     stream.Free;
  20.   end;
  21. end;
 
« Last Edit: May 03, 2016, 10:40:46 pm by wp »

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: TStringlist.Items.LoadFromFile unicode ??
« Reply #2 on: May 03, 2016, 10:37:41 pm »
But its only showing "??" instead of the string.

A TStringList is a convenient container for text data, not a GUI component.
So how are you "showing" the text data loaded from a file via the stringlist?

penpen

  • New Member
  • *
  • Posts: 23
Re: TStringlist.Items.LoadFromFile unicode ??
« Reply #3 on: May 04, 2016, 09:28:43 pm »
Awesome. Thanks guys :)

 

TinyPortal © 2005-2018