procedure TForm1.FormCreate(Sender: TObject);
var
  txt: TextFile;
  tempbuffer: widestring;
  fs: TFileStream;
begin
  Randomize();
  tempbuffer := 's我工a1';
  AssignFile(txt, ExtractFilePath(Application.ExeName) + '1.txt');
  Rewrite(txt);
  Writeln(txt, tempbuffer);
  CloseFile(txt);
  fs := TFileStream.Create(ExtractFilePath(Application.ExeName) + '2.txt',
    fmCreate);
  fs.Write(#$FF#$FE, 2);
  fs.Write(tempbuffer[1], Length(tempbuffer) * 2);
  fs.Free;
  OldProc := Pointer(Windows.setwindowlong(self.Handle, Windows.GWL_WNDPROC,
    longint(@NewProc)));end;
同样是写的widestring,1.txt里打开看是ansi,2.txt里打开看是正常的unicode,这是为什么?

解决方案 »

  1.   


    没有错误。只是用textfile写widestring,写进后,居然是ansi的。
      

  2.   


    procedure TForm1.FormCreate(Sender: TObject);
    var
      txt: TextFile;
      tempbuffer: string;
      fs: TFileStream;
      stlist:TStringList;
    begin
      Randomize();
      tempbuffer := 's我工a1';
      AssignFile(txt, ExtractFilePath(Application.ExeName) + '1.txt');
      Rewrite(txt);
      Writeln(txt, tempbuffer);
      CloseFile(txt);
      fs := TFileStream.Create(ExtractFilePath(Application.ExeName) + '2.txt',
        fmOpenRead);
      fs.Write(#$FF#$FE, 2);
      fs.Write(tempbuffer[1], Length(tempbuffer) * 2);
      fs.Free;
      stlist:=TStringList.Create;
      stlist.Add(tempbuffer);
      stlist.SaveToFile(ExtractFilePath(Application.ExeName)+'3.txt');
      stlist.Free;end;再加一个stringlist的。1.txt和3.txt都是ansi2.txt是unicodewhy?
      

  3.   

    fs := TFileStream.Create(ExtractFilePath(Application.ExeName) + '2.txt',
        fmOpenRead);
    这个是打开文件仅读的方式,文件必须先存在,且你写的内容只是到内存流,你怎么检查到这个文件是写到了UNICODE码?在你的代码中根本没有改变2.txt文件的代码(fs.Write(#$FF#$FE, 2);
      fs.Write(tempbuffer[1], Length(tempbuffer) * 2);这个只是写到内存的文件流中)。
      

  4.   

    我后面的代码是贴错了,你看1楼的。关键重点不在这里,我问的是为什么用textfile和stringlist写widestring,会变成ansi?
    我用的是delphi xe
      

  5.   

    昨天正在研究这个编码问题
    用AssignFile rewrite方式我也只会写入ANSI 暂时也没搞懂StringList就容易了 它可以设置编码//------ 字符串列表保存TXT文本 相比最简单
    function SaveToTxt(const FN, Data: string): Boolean;
    var
      SS_Save: TStrings;
    begin
      Result := False;
      SS_Save := TStringList.Create;
      try
        SS_Save.Text := Data;
        SS_Save.SaveToFile(FN, TEncoding.Unicode);
        if FileExists(FN) then
          Result := True;
      finally
        FreeAndNil(SS_Save);
      end;
    end;文件流方式也还在试验中
      

  6.   

    又从万一的博客学了一招
    用 TStreamWrite写 TStreamReader 读写不错
    http://www.cnblogs.com/del/archive/2009/10/12.html//----- 保存到txt
    function SaveToTxt(const FN, Data: string): Boolean;
    var
      FS: TStreamWriter;
    begin
      FS := TStreamWriter.Create(FN, True, TEncoding.Unicode);  //True表追加文本
      FS.WriteLine(Data);   //函数重载 可以写入很多数据类型
      //FS.Write(Data);
      FS.Close;
      FS.Free;
    end;
      

  7.   


    想不明白的是XE中,string默认就是widestring.为什么用textfile还是ansi.
    而stringlist也是默认wide的。居然也是ansi。难道是设计者为了方便大家使用?这样也太不规范了。
      

  8.   

    兄台的LOGO这么大个易字,难道是易友?