How to save a memo as unicode

对着背影说爱祢 提交于 2021-01-28 03:43:54

问题


I am using Delphi 7, How can I save a Memo as a Unicode text file, I find some example for save it as UTF-8 text file, but I need an example for saving file as unicode. Thanks for any help


回答1:


You need to use a control that supports Unicode. Delphi 7 TMemo does not. Which means that your real problem is not so much saving the content, but admitting the content in the first place.

You should deal with this by switching to the TNT Unicode components. Once you start using the TNT Unicode components, the TNT Unicode memo supports saving the contents as Unicode.




回答2:


UTF-8 is Unicode. It is just a byte encoding scheme for Unicode data. If you really mean that you need to save the file as UTF-16 instead of UTF-8, that is a different question.

The best option is to use a Unicode-based Memo control and let it handle the Unicode data for you. You really should upgrade to a modern Unicode-based Delphi version (Delphi 2009 or later) and let it handle Unicode conversions for you. If you stay with an old ANSI-based Delphi version (Delphi 2007 or earlier), then you should use third-party Unicode UI controls, like David suggested.

However, if you stick with the native VCL ANSI-based Memo, you can still accomplish what you are asking for, you will just have to manage the conversion manually in your code. You can convert the TMemo's ANSI-based data to UTF-16 using the WideString string type (which internally uses MultiByteToWideChar() to convert ANSI data to UTF-16), and then write the UTF-16 data to a file.

For example:

var
  BOM: WideChar;
  FS: TFileStream;
  WS: WideString;
  I: Integer;
begin
  FS := TFileStream.Create('MyUnicodeFile.txt', fmCreate);
  try
    BOM := WideChar($FEFF);
    FS.WriteBuffer(BOM, SizeOf(BOM));
    For I := 0 to Memo1.Lines.Count-1 do
    begin
      WS := WideString(Memo1.Lines[I] + sLineBreak);
      FS.WriteBuffer(PWideChar(WS)^, Length(WS) * SizeOf(WideChar));
    end;
  finally
    FS.Free;
  end;
end;


来源:https://stackoverflow.com/questions/36687531/how-to-save-a-memo-as-unicode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!