//from
http://kingron.myetang.com/zsfunc0d.htm
(*//
标题:充分利用pascal字符串类型
说明:和PChar不同,string可以保存#0字符在其中;示例文件、内存流字符串之间转换
设计:Zswang
日期:2002-01-25
支持:wjhu111@21cn.com
//*)
///////Begin Source
function StringToFile(mString: string; mFileName: TFileName): Boolean;
{ 返回字符串保存到文件是否成功 }
var
vFileChar: file of Char;
I: Integer;
begin
{$I-}
AssignFile(vFileChar, mFileName);
Rewrite(vFileChar);
for I := 1 to Length(mString) do Write(vFileChar, mString[I]);
CloseFile(vFileChar);
{$I+}
Result := (IOResult = 0) and (mFileName <> '');
end; { StringToFile }
function FileToString(mFileName: TFileName): string;
{ 返回从文件载入字符串 }
var
vFileChar: file of Char;
vChar: Char;
begin
Result := '';
{$I-}
AssignFile(vFileChar, mFileName);
Reset(vFileChar);
while not Eof(vFileChar) do begin
Read(vFileChar, vChar);
Result := Result + vChar;
end;
CloseFile(vFileChar);
{$I+}
end; { FileToString }
function StreamToString(mStream: TStream): string;
{ 将内存流转换成字符串 }
var
I: Integer;
begin
Result := '';
if not Assigned(mStream) then Exit;
SetLength(Result, mStream.Size);
for I := 0 to Pred(mStream.Size) do try
mStream.Position := I;
mStream.Read(Result[Succ(I)], 1);
except
Result := '';
end;
end; { StreamToString }
function StringToStream(mString: string; mStream: TStream): Boolean;
{ 返回将字符串保存到内存流是否成功 }
var
I: Integer;
begin
Result := True;
try
mStream.Size := 0;
mStream.Position := 0;
for I := 1 to Length(mString) do mStream.Write(mString[I], 1);
except
Result := False;
end;
end; { StringToStream }
///////End Source
///////Begin Demo
procedure TForm1.Button1Click(Sender: TObject);
var
vMemoryStream: TMemoryStream;
begin
Memo1.Text := FileToString('C:\WINDOWS\Desktop\1.txt');
vMemoryStream := TMemoryStream.Create;
try
Memo1.Lines.SaveToStream(vMemoryStream);
Memo2.Text := StreamToString(vMemoryStream);
finally
vMemoryStream.Free;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
vMemoryStream: TMemoryStream;
begin
StringToFile(Memo2.Text, 'C:\WINDOWS\Desktop\1.txt');
vMemoryStream := TMemoryStream.Create;
try
StringToStream(Memo2.Text, vMemoryStream);
vMemoryStream.Position := 0;
Memo1.Lines.LoadFromStream(vMemoryStream);
finally
vMemoryStream.Free;
end;
end;
///////End Demo
http://www.delphitop.com/html/zifuchuan/1711.html