Search code examples
stringdelphizipmemorystreamtmemo

Delphi - Text from file in ZIP to Memo


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!


Solution

  • Try replacing this code:

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

    with a call to SetString

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

    like in this question