请教关于AnsiString,UTF8String,存成文件后,由C#读取中文出乱码的问题

啥都得学呀 2013-11-07 09:22:20
开发环境D2007,源代码提供了Add(const aValue: AnsiString)的方法,通过此方法把字符串保存文件后C#读的时候,中文会出乱码。我想问,如何增加重写方法,能让C#默认读的时候不出乱码。
C#那边的代码不能修改。

我个人觉得Add(const aValue: AnsiString);修改成UTF8String可能好用。但是不敢随便改,怕出错。请高手指点!

procedure TSegmentBuffer.Add(const aValue: PAnsiChar; aCnt: integer);
var
p: PAnsiChar;
tmp: integer;
begin
p := aValue;
// define size of unused memory in current buffer segment
tmp := FLast^.Size - FLast^.Count;
// if you do not have enough space in the buffer then copy the "unused" bytes
// and reduce current segment
if aCnt > tmp then begin
System.Move(p^, FLast^.Data[FLast^.Count], tmp);
Inc(FLast^.Count, tmp);
Inc(FCount, tmp);
Inc(p, tmp);
Dec(aCnt, tmp);
// add another segment of the larger buffer size
tmp := FLast^.Size;
if tmp < aCnt then tmp := aCnt;
AddSegment(tmp * 2);
end;
if aCnt > 0 then begin
Move(p^, FLast^.Data[FLast^.Count], aCnt);
Inc(FCount, aCnt);
Inc(FLast^.Count, aCnt);
end;
end;

procedure TSegmentBuffer.Add(const aValue: AnsiString);
var len: integer;
begin
len := Length(aValue);
if len > 0 then
Add(@aValue[1], len);
end;

procedure TSegmentBuffer.Add(const aValue: AnsiChar);
begin
Add(@aValue, 1);
end;

procedure TSegmentBuffer.SaveToFile(const FileName: string);
var stream: TStream;
begin
stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(stream);
finally
stream.Free;
end;
end;

procedure TSegmentBuffer.SaveToStream(Stream: TStream);
var segment: PSegment;
begin
segment := FFirst;
while segment <> nil do begin
Stream.WriteBuffer(segment^.Data[0], segment^.Count);
segment := segment^.Next;
end;
end;
...全文
156 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
啥都得学呀 2013-11-07
  • 打赏
  • 举报
回复
进一步追问,即使保存文件解决了,那么,如果我要发送一个流数据给C#读呢?确切的说,我要用SOCKET把一个流发送给C#,那还会出现乱码的吧!
啥都得学呀 2013-11-07
  • 打赏
  • 举报
回复
请楼上的给点代码把!
武稀松 2013-11-07
  • 打赏
  • 举报
回复
C#读文件默认是Unicode吧. 要么你给你的文件增加个BOM,要么存成Unicode. C#我会自动更具BOM判断编码.C#那边的代码他很有可能他没有使用Encoding的方法解码数据.而是直接把数据从流读到了string里面,你最好采用直接保存Unicode数据的方案

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧