Author: Pieter Valentijn
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.
1 procedure TForm1.ThisISHowIPutFilesIn;
2 var
3 ABigFileStream, SomeSmallFiles: TMemoryStream;
4
5 begin
6 ABigFileStream := TMemoryStream.Create;
7 try
8 SomeSmallFiles := TMemoryStream.Create;
9 try
10 SomeSmallFiles.LoadFromFile('C:\SomeSmalFile1.txt');
11 AddToStream(SomeSmallFiles, ABigFileStream);
12 SomeSmallFiles.LoadFromFile('C:\SomeSmalFile2.txt');
13 AddToStream(SomeSmallFiles, ABigFileStream);
14 // enz
15 finally
16 SomeSmallFiles.Free;
17 end;
18 ABigFileStream.SaveToFile('C:\MrBig.DDD')
19 finally
20 ABigFileStream.free;
21 end;
22 end;
23
24 procedure TForm1.ThisISHowIGetStufOut;
25 var
26 ABigFileStream, SomeSmallFiles: TMemoryStream;
27
28 begin
29 ABigFileStream := TMemoryStream.Create;
30 try
31 ABigFileStream.LoadFromFile('C:\MrBig.DDD');
32 SomeSmallFiles := TMemoryStream.Create;
33 try
34 GetFromStream(ABigFileStream, SomeSmallFiles, 0);
35 SomeSmallFiles.SaveToFile('C:\SomeSmalFile1.txt');
36 GetFromStream(ABigFileStream, SomeSmallFiles, 1);
37 SomeSmallFiles.SaveToFile('C:\SomeSmalFile2.txt');
38 // enz
39 finally
40 SomeSmallFiles.Free;
41 end;
42 finally
43 ABigFileStream.free;
44 end;
45 end;
46
47 procedure TForm1.AddToStream(Source, Dest: TStream);
48 var
49 Size: Integer;
50 begin
51 Source.position := 0;
52 // Keep the size by puting it in the first byte
53 Size := Source.Size;
54 Dest.write(Size, SizeOf(Integer));
55 Dest.CopyFrom(Source, Source.size);
56 end;
57
58 procedure TForm1.GetFromStream(Source, Dest: TStream; Index: Integer);
59 var
60 Size, I: Integer;
61
62 begin
63 Source.Position := 0;
64 for i := 0 to index - 1 do
65 begin
66 Source.read(Size, SizeOf(Integer));
67 Source.Position := Source.Position + Size;
68 end;
69 // if where all the way up the file pointer then someting went wrong :(
70 if Source.position = Source.Size then
71 raise EAccessViolation.Create('Index Out Of Bounds');
72 // Get the desired file size
73 Source.read(Size, SizeOf(Integer));
74 // Clear Dest Buffer
75 Dest.Position := 0;
76 Dest.Size := 0;
77 Dest.CopyFrom(Source, Size);
78 end;
|