在某些ZIP文件中,我有文件head.txt。我想将此文件中的文本复制到我的表单上的TMemo。这是我的代码:
procedure TformMain.LoadProject(InputFileName: string);
var
MS: TMemoryStream;
zip: TZipForge;
txt: string;
begin
MS := TMemoryStream.Create;
try
zip := TZipForge.Create(nil);
try
with zip do begin
FileName := InputFileName;
OpenArchive(fmOpenReadWrite);
ExtractToStream('head.txt', MS);
CloseArchive;
end;
finally
zip.Free;
end;
MS.Seek(0, soFromBeginning);
SetLength(txt, MS.Size);
MS.Write(txt[1], MS.Size);
finally
MS.Free;
end;
if Length(txt) > 0 then Memo1.Lines.Text := txt;
end;
但它不起作用。 在我的ZIP文件的head.txt中:
123456
abcdef
xxxx
,备忘录中的结果是:
auto-suggest dropdow
感谢您的帮助!
答案 0 :(得分:4)
问题在于,您不是使用Read方法将内存流中的数据读入txt变量,而是将txt变量中的数据写入内存流。
所以你的代码看起来应该更像这个
procedure TformMain.LoadProject(InputFileName: string);
var
MS: TMemoryStream;
zip: TZipForge;
txt: string;
begin
MS := TMemoryStream.Create;
try
zip := TZipForge.Create(nil);
try
with zip do begin
FileName := InputFileName;
OpenArchive(fmOpenReadWrite);
ExtractToStream('head.txt', MS);
CloseArchive;
end;
finally
zip.Free;
end;
MS.Seek(0, soFromBeginning);
SetLength(txt, MS.Size);
MS.Read(txt, MS.Size);
finally
MS.Free;
end;
if Length(txt) > 0 then Memo1.Lines.Text := txt;
end;
我还没有测试过它。
但是既然你想将该文件中的文本加载到Memo中,你可以通过删除txt变量及其所需的所有烦恼来简化这一过程,并将文本直接从内存流加载到备忘录中,如下所示:
Memo1.Lines.LoadFromStream(MS);
所以你的最终代码应如下所示:
procedure TformMain.LoadProject(InputFileName: string);
var
MS: TMemoryStream;
zip: TZipForge;
begin
MS := TMemoryStream.Create;
try
zip := TZipForge.Create(nil);
try
with zip do begin
FileName := InputFileName;
OpenArchive(fmOpenReadWrite);
ExtractToStream('head.txt', MS);
CloseArchive;
end;
finally
zip.Free;
end;
MS.Seek(0, soFromBeginning);
Memo1.Lines.LoadFromStream(MS);
finally
MS.Free;
end;
end;
答案 1 :(得分:2)
尝试替换此代码:
MS.Seek(0, soFromBeginning);
SetLength(txt, MS.Size);
MS.Write(txt[1], MS.Size);
SetString(txt, PAnsiChar(MS.Memory), MS.Size);
中