Mirror

How to save and load a TList to / from a stream (Views: 40)


Problem/Question/Abstract:

Can anyone tell me how to stream a TList to a file? Given:

type
  PassWordItem = class(TObject)
    accountName: string[30];
    userName: string[25];
    passWd: string[10];
  end;

and...

PassWdList: TList;

How do I stream the contents of PassWdList to a file, and subsequently load TList from the file?

Answer:

Lets add a couple of methods to the PassWordItem class:


PassWordItem = class(TObject)
public
  accountName: string[30];
  userName: string[25];
  passWd: string[10];

  procedure SaveToStream(s: TStream);
  constructor CreatefromStream(S: TStream);
end;


With that you can write two procedures (or methods of a TPasswordList class derived from TList):


procedure SavePasswordlist(pwl: TLIst; S: TStream);
var
  i: Integer;
begin
  Assert(Assigned(pwl));
  Assert(Assigned(S));
  i := pwl.count;
  S.Write(i, sizeof(i));
  for i := 0 to pwl.count - 1 do
    PasswordItem(pwl[i]).SaveToStream(S);
end;

procedure LoadPasswordList(pwl: TList; S: TStream);
var
  count, n: Integer;
begin
  Assert(Assigned(pwl));
  Assert(Assigned(S));
  S.Read(count, sizeof(count));
  pwl.Capacity := count;
  for n := 1 to count do
    pwl.Add(PasswordItem.CreatefromStream(S));
end;

procedure Passworditem.SaveToStream(s: TStream);
begin
  Assert(Assigned(S));
  S.Write(accountname, Sizeof(accountname));
  S.Write(username, sizeof(username));
  S.Write(passwd, sizeof(passwd));
end;


constructor CreatefromStream(S: TStream);
begin
  Assert(Assigned(S));
  inherited Create;
  S.Read(accountname, Sizeof(accountname));
  S.Read(username, sizeof(username));
  S.Read(passwd, sizeof(passwd));
end;

<< Back to main page