Read/Write file from a .zip archive - delphi

Should I work with files within the archive file. (Read - write). By the following code, I get a list of files on my needs.
Zip := TZipFile.Create;
try
Zip.Open(FilePath, TZipMode.zmRead);
For File_Name in Zip.FileNames do
begin
//some code
end;
finally
Zip.Close;
FreeAndNil(Zip);
end;
I used the TZipFile.Read method to reads a file from a .zip archive .
This method returns the complete content of file into a buffer of type TByte. But just need to read a 1MB file from the beginning, not the complete file.
After reading and analyzing a 1MB file, if needed, should be read complete file and make changes to the file and re-save the file to archive.
Memory and speed of the program is very important. I used to set the buffer size of the function SetLength, unfortunately complete content of file files are stored in the buffer.
What do you think?

Use the overloaded version of TZipFile.Read() that returns a TStream instead of a TBytes. That way, you do not have to read the entire file into memory, and can read just its beginning bytes as needed.
Unfortunately, there is no way to modify data inside of a zip archive using TZipFile. Although you can Extract() a particular file, modify it externally as needed, and then Add() it back into TZipFile, there is no way to remove/replace a given file in TZipFile. TZipFile is a simple framework, it can only read a zip archive and add new files to it, nothing else. If you need more control over a zip archive, you are better off using a more complete third-party solution, such as ZipForge.

Related

How do I add file data to my EXE file at RunTime in delphi

I have created an application that manage an embedded database
My Customer want this application to be in one file
My Task is to modify my application so it can extract database file from exe , edit it ,and include if again at run time not in compile time
An executable file cannot be modified while the executable is running. Which means that in order to achieve your goal you would need another process. You could do the following:
Start your process.
Extract the DB from the process image.
Make changes to the DB.
Extract another executable file from the original image.
Start a second process based on this extracted images.
Terminate the first process.
Have the second process update the disk image with the modified DB.
Frankly this is a quite terrible idea. Don't even attempt this. The complexity serves no useful purpose, and the whole concept feels brittle.
Keep the data in a file separate from the program, as nature intended.
This is of course a bad idea, just think of what virusscanners are going to think of this approach. Also what happens if the exe crashes, will your db now lose all of its updates?
You can have the exe create a self extracting archive containing all the files needed.
This works as follows (the steps are the same as #David above, except that the components listed do most of the work for you).
Extract self extracting zip.
this contains: the real exe to be started upon extract
the database
some files needed to recreate a new self extracting exe
Upon closing the program it will create a new zip file, including:
Itself (in readonly form)
The database
some files needed to recreate a new self extracting exe
It will then transform the zip-file into a new self-extracting exe
the new self-extracting archive will start the exe included in it's embedded zip file as per #1.
Here's some sample code from sfx-zip-delphi.
program SelfExtractingZip;
{$APPTYPE CONSOLE}
uses
// Add a ZipForge unit to the program
SysUtils, ZipForge, Classes;
var
archiver : TZipForge;
begin
// Create an instance of the TZipForge class
archiver := TZipForge.Create(nil);
try
with archiver do
begin
// Set the name of the archive file we want to create.
// We set extension to exe because we create a SFX archive
FileName := 'C:\test.exe';
// See SFXStub demo in ZipForge\Demos\Delphi folder
// to learn how to create a SFX stub
SFXStub := 'C:\SFXStub.exe';
// Because we create a new archive,
// we set Mode to fmCreate
OpenArchive(fmCreate);
// Set base (default) directory for all archive operations
BaseDir := 'C:\';
// Add the C:\test.txt file to the archive
AddFiles('c:\test.txt');
CloseArchive();
end;
except
on E: Exception do
begin
Writeln('Exception: ', E.Message);
// Wait for the key to be pressed
Readln;
end;
end;
end.
Solutions for self extracting exe's
Paid
If you want a paid solution: http://www.componentace.com/sfx-zip-delphi.htm
Free
Or free: http://tpabbrevia.sourceforge.net/Self-Extracting_Archives
The abbrevia docs for self-extracting files are here: https://sourceforge.net/projects/tpabbrevia/postdownload?source=dlp
See page 293.

Remove zip file item path with Abbrevia

Is it possible to remove a zip file item's path with Abbrevia? After looking at the source code I can not find a method to remove the path of a file. Has anyone tried to do this and if so, how?
EDIT
I am displaying the contents of a zipfile in a TAbListView where the path for each file is stored in the archive. The items were added to the zip file with the StoreOptions set at [soStripDrive], so the path is stored in the TAbListView.Items.Item[I].Subitem[9] for each file in the zip file. I am looking to strip the paths and then save the archive so that none of the files have paths.
Paths before removal
TAbListView.Items.Item[0].Subitem[9] := \DelphiXE4\Projects\Abbrevia\Unit1.pas
TAbListView.Items.Item[1].Subitem[9] := \DelphiXE4\Projects\Abbrevia\Unit1.dfm
Paths after removal
TAbListView.Items.Item[0].Subitem[9] := '';
TAbListView.Items.Item[1].Subitem[9] := '';
So the zipped items do not have any paths.
AFAICT, you can't change the name in the archive (zip) without actually extracting the file and then putting it back in without storing the path in the first place.
The obvious place to try and change it would be with TAbZipItem.StoredPath, but that's read only; using TAbZipItem.FileName works fine when compiling and running, but has no effect. Nothing you do in the TAbsListView will change anything, as it's just displaying content and has nothing to do with the underlying zip archive.

ILASM does not set FileVersion

I have an .il file which I can compile without any problems. I can strong name it and so without any issues. But I am not able to set the file version via the attribute as I would expect it. How can I set the FileVersion for an assembly when using ilasm?
If I do a round trip I get always a .res file which does contain only binary data which is not readable. What is inside this res file and can I edit it?
The code does not work
.assembly myAssembly
{
.custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = { string('1.2.3.4') }
The issue can be solved by using the .res file. It is not sufficient to do a round trip with ildasm and ilasm. The IL file does not reference the .res file. I had to add it to the ilasm call manually. The data in the res file seemed to contain the infos which are written into the PE header which is ok for me.
The final command line needed was
ilasm test.il /dll /res:test.res
I still do not know what exactly is inside the res file but I can exhange it with the meta data information of any other assemlby that I create manually and then decompile it to replace the metadata of the original assembly as I need.
It seems not many people are doing such stuff.

How do I use a custom AVI with TAnimate?

I have an AVI file that I pulled from shell32 using Resources Extract. I would like to use this with TAnimate but I can't figure out how to load this file.
I succesfully loaded the AVI into a .RES file using DelphiDabbler's rcdatacreator program (you have to download the "worked example" to get rcdatacreator. However, my issue now is figuring out how to extract the AVI file from the .RES and supplying it to TAnimate.
I am using Delphi 2010:
Any help is appreciated.
As Andreas mentioned (in his now deleted answer), you don't need to use an external tool to add the resource in recent versions of Delphi.
Use Project/Resources and Images... from the IDE menu. Add a new resource by browsing to the folder your .AVI file is in, give it a name, and type in AVI for the Resource Type. (It's not in the list, but you can add it.)
At runtime, use the following code:
// I used CoolAVI as the resource name in my image above,
// so that's the name I need to use here.
Animate1.ResName := 'COOLAVI';
Animate1.Active := True;

How I Compile Resources into my Application and Access them?

How can I make a single executable package that contains DLL and Image Resource Files?
Then how do I extract them from my Executable at Runtime?
Option 1 using the IDE (Delphi 2007 or Higher):
You can click the Project menu, then select Resources..., which you can load any file into. For your purpose this would be RC_DATA.
Option 2 without the IDE
If you do not have the above option, you will need to use the BRCC32 (Borland Resource Compiler) to create a .RES file from RC file, which you then link to your Application. To link Resource files without using the IDE, try the following:
Lets say for example we want to add a a couple of DLL files, and the name of the DLL files are MyLib1.dll and MyLib2.dll, to add this open Notepad, and type the following:
MYLIB1 RCDATA "..\MyLib1.dll"
MYLIB2 RCDATA "..\MyLib2.dll"
Make sure the ..\xxx.dll paths are correct, so obviously you need to edit that.
Now you need to save this as a .rc file, so File>Save As..(make sure the dropdown filter is All Files .) and name it MyResources.rc. Now you need to use the Resource Compiler to generate the Res file, using this console command:
BRCC32 MyResources.RC
You can write that command by using the Command Prompt, Start Menu > Run > cmd.exe, alternatively you can find the BRCC32.exe inside the bin folder of your Delphi setup and drag the MyResource.RC file onto.
This will create a Res file named MyResources.RES which you can include inside the Main Delphi form of your Application, like so:
{$R *.dfm}
{$R MyResources.res}
you can extract the resources by using something like this:
procedure ExtractResource(ResName: String; Filename: String);
var
ResStream: TResourceStream;
begin
ResStream:= TResourceStream.Create(HInstance, ResName, RT_RCDATA);
try
ResStream.Position:= 0;
ResStream.SaveToFile(Filename);
finally
ResStream.Free;
end;
end;
What I've found out to be convenient, is to use a .zip container.
Then you'll have two implementations:
Append some .zip content to an existing .exe, and the .exe code will retrieve the .zip content on request;
Embed the .zip content as a resource, then extract on request each content.
Solution 1 will add the .zip content after compilation. Whereas 2 will add the .zip content at compilation. For a setup program, I think solution 1 makes sense to me. For a way of retrieving some needed files (libraries, and even bitmaps or text) which are linked to a particular exe release, solution 2 could be envisaged.
Using .zip as format make it easy to parse the content, and allow compression. Using a tool like TotalCommander, you can even read the .zip file content with Ctrl+PgDown over the .exe. Very convenient.
You'll find in this link how you implement solution 1, and in this link (same page, but another post) how to use the TZipRead.Create() constructor to directly access to a .zip bundled as resource. You'll find in our repository how it works with working applications: e.g. how we embedded icons, textual content and graphviz + spell-checker libraries in the SynProject executable.
About performance, there is no difference between the two solutions, at least with our code. Both use memory mapped files to access the content, so it will be more or less identical: very fast.

Resources