我有一个带有UTF8编码的文本文件,我在delphi 2009中创建了一个带有opendialoge,备忘录和按钮的应用程序并编写了这段代码:
if OpenTextFileDialog1.Execute then
Memo1.Lines.LoadFromFile(OpenTextFileDialog1.FileName);
当我运行我的应用程序时,我点击按钮并选择我的文本文件,在备忘录中我看到:
“Œط¯ط±ط¢''.................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
字符未正确显示。 我该如何解决这个问题?
答案 0 :(得分:5)
可以在OpenTextFile对话框中选择编码格式。 OpenTextFileDialog.Encodings表示可以使用的编码列表,默认列表:ANSI,ASCII,Unicode,BigEndian,UTF8和UTF7。
// Optionally add Encoding formats to the list:
FMyEncoding := TMyEncoding.Create;
OpenTextFileDialog1.Encodings.AddObject('MyEncoding', FMyEncoding);
// Don't forget to free FMyEncoding
var
Encoding : TEncoding;
EncIndex : Integer;
Filename : String;
begin
if OpenTextFileDialog1.Execute(Self.Handle) then
begin
Filename := OpenTextFileDialog1.FileName;
EncIndex := OpenTextFileDialog1.EncodingIndex;
Encoding := OpenTextFileDialog1.Encodings.Objects[EncIndex] as TEncoding;
// No Encoding found in Objects, probably a default Encoding:
if not Assigned(Encoding) then
Encoding := StandardEncodingFromName(OpenTextFileDialog1.Encodings[EncIndex]);
//Checking if the file exists
if FileExists(Filename) then
//Display the contents in a memo based on the selected encoding.
Memo1.Lines.LoadFromFile(FileName, Encoding)