-2

In some ZIP file I have file head.txt. I want to copy text from this file to TMemo on my form. Here's my code:

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;

But it doesn't work. In head.txt in my ZIP file is:

123456
abcdef
xxxx

and the result in Memo is:

auto-suggest dropdow

Thanks for help!

4

2 回答 2

4

问题是,不是使用 Read 方法将 Memory Stream 中的数据读取到 txt 变量中,而是实际上将 txt 变量中的数据写入 Memory Stream 中。

所以你的代码应该看起来更像这样

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;

我还没有测试出来。

但是,由于您想将该文件中的文本加载到备忘录中,您可以通过删除 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;
于 2015-07-22T21:44:51.750 回答
2

尝试替换此代码:

MS.Seek(0, soFromBeginning);
SetLength(txt, MS.Size);
MS.Write(txt[1], MS.Size);

打电话给SetString

SetString(txt, PAnsiChar(MS.Memory), MS.Size);

就像在这个问题中

于 2015-07-22T21:32:04.197 回答