Search code examples
delphiunicodedelphi-xecodepages

How to use Delphi XE's TEncoding to save Cyrillic or ShiftJis text to a file?


I'm trying to save some lines of text in a codepage different from my system's such as Cyrillic to a TFileStream using Delphi XE. However I can't find any code sample to produce those encoded file ?

I tried using the same code as TStrings.SaveToStream however I'm not sure I implemented it correctly (the WriteBom part for example) and would like to know how it would be done elsewhere. Here is my code:

FEncoding := TEncoding.GetEncoding(1251);
FFilePool := TObjectDictionary<string,TFileStream>.Create([doOwnsValues]);

//...

procedure WriteToFile(const aFile, aText: string);
var
  Preamble, Buffer: TBytes;
begin
  // Create the file if it doesn't exist
  if not FFilePool.ContainsKey(aFile) then
  begin
    // Create the file
    FFilePool.Add(aFile, TFileStream.Create(aFile, fmCreate));
    // Write the BOM
    Preamble := FEncoding.GetPreamble;
    if Length(Preamble) > 0 then
     FFilePool[aFile].WriteBuffer(Preamble[0], Length(Preamble));
  end;
  // Write to the file
  Buffer := FEncoding.GetBytes(aText);
  FFilePool[aFile].WriteBuffer(Buffer[0], Length(Buffer));
end;

Thanks in advance.


Solution

  • If I understand it's pretty simple. Declare an AnsiString with affinity for Cyrillic 1251:

    type
      // The code page for ANSI-Cyrillic is 1251
      CyrillicString = type AnsiString(1251);
    

    Then assign your Unicode string to one of these:

    var
      UnicodeText: string;
      CyrillicText: CyrillicString;
    ....
      CyrillicText := UnicodeText;
    

    You can then write CyrillicText to a stream in the traditional manner:

    if Length(CyrillicText)>0 then
      Stream.WriteBuffer(CyrillicText[1], Length(CyrillicText));
    

    There should be no BOM for an ANSI encoded text file.