Delphi中的内存流还算比较好用的,有时候需要与字符串互转,网络上找到几个函数保存备用!
//字符串保存到文件中,返回成功与否
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;
//从文件中读出字符串
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;
//把内存流中的字节数组转化为string类型
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;
//把字符串存入内存流中,返回成功与否
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;
标签:mString,end,Delphi,mFileName,内存,字符串,vFileChar,mStream,Result
From: https://www.cnblogs.com/YXGust/p/16617445.html