2005. április 11., hétfő

Getting a lot of files in one stream


Problem/Question/Abstract:

How to get a lot of files in one stream
And get it back to :)

Answer:

Some times i want to Have multiple files in a stream couse then i dont have to send a lot of files but just one .

So heres a little code sniped to get it in and out again.

procedure TForm1.ThisISHowIPutFilesIn;
var
  ABigFileStream, SomeSmallFiles: TMemoryStream;

begin
  ABigFileStream := TMemoryStream.Create;
  try
    SomeSmallFiles := TMemoryStream.Create;
    try
      SomeSmallFiles.LoadFromFile('C:\SomeSmalFile1.txt');
      AddToStream(SomeSmallFiles, ABigFileStream);
      SomeSmallFiles.LoadFromFile('C:\SomeSmalFile2.txt');
      AddToStream(SomeSmallFiles, ABigFileStream);
      // enz
    finally
      SomeSmallFiles.Free;
    end;
    ABigFileStream.SaveToFile('C:\MrBig.DDD')
  finally
    ABigFileStream.free;
  end;
end;

procedure TForm1.ThisISHowIGetStufOut;
var
  ABigFileStream, SomeSmallFiles: TMemoryStream;

begin
  ABigFileStream := TMemoryStream.Create;
  try
    ABigFileStream.LoadFromFile('C:\MrBig.DDD');
    SomeSmallFiles := TMemoryStream.Create;
    try
      GetFromStream(ABigFileStream, SomeSmallFiles, 0);
      SomeSmallFiles.SaveToFile('C:\SomeSmalFile1.txt');
      GetFromStream(ABigFileStream, SomeSmallFiles, 1);
      SomeSmallFiles.SaveToFile('C:\SomeSmalFile2.txt');
      // enz
    finally
      SomeSmallFiles.Free;
    end;
  finally
    ABigFileStream.free;
  end;
end;

procedure TForm1.AddToStream(Source, Dest: TStream);
var
  Size: Integer;
begin
  Source.position := 0;
  // Keep the size by puting it in the first byte
  Size := Source.Size;
  Dest.Write(Size, SizeOf(Integer));
  Dest.CopyFrom(Source, Source.size);
end;

procedure TForm1.GetFromStream(Source, Dest: TStream; Index: Integer);
var
  Size, I: Integer;

begin
  Source.Position := 0;
  for i := 0 to index - 1 do
  begin
    Source.Read(Size, SizeOf(Integer));
    Source.Position := Source.Position + Size;
  end;
  // if where all the way up the file pointer then someting went wrong :(
  if Source.position = Source.Size then
    raise EAccessViolation.Create('Index Out Of Bounds');
  // Get the desired file size
  Source.Read(Size, SizeOf(Integer));
  // Clear Dest Buffer
  Dest.Position := 0;
  Dest.Size := 0;
  Dest.CopyFrom(Source, Size);
end;

Nincsenek megjegyzések:

Megjegyzés küldése