About this Contribution

This contribution allows you to use 7-zip archive format DLLs in your programs written in .NET languages.

I created this module for my own project to have the ability to work with archives. Currently my project only has extract capabilities, so only this part of 7-Zip interface translated to C#. Later I plan to translate compress capability as well. For now if you need such functionality you can implement it by yourself, with this code, and the 7-Zip source code.

This translation is tested and already working in my own project.

Implementation Details

All communication with archive DLLs is done with COM-like interfaces (why COM-like, and not COM can be see in the known issues section). Callbacks are also implemented as interfaces.

Every DLL contains a class that can implement one or more interface. Some formats allows only extracting, some also provide compress abilities. Public interfaces translated to C#:

IProgress - basic progress callback

IArchiveOpenCallback - archive open callback

ICryptoGetTextPassword - callback for prompt password for archive

IArchiveExtractCallback - extract files from archive callback

IArchiveOpenVolumeCallback - open additional archive volumes callback

ISequentialInStream - simple read-only stream interface

ISequentialOutStream - simple write-only stream interface

IInStream - input stream interface with seek capability

IOutStream - output stream interface

IInArchive - main archive interface

Every DLL export function is for creating archive class handlers and functions in order to get archive format properties. These functions are translated as .NET delegates:

Update (1.3): In 7-Zip 4.45 there are some changes in the DLL interface. Now all archive formats and compression codecs are implemented as one big DLL. So several new exported functions (and delegates for these functions in translation) are added to handle several archive handler classes in one DLL.

Points of Interest

7-Zip interfaces uses variants (PropVariant) for property values. C# does not support such variants as classes and all such parameters are implemented in C# as IntPtr. This is done for compatibility and because I prefer not to use unsafe code in my projects.

Fortunately a managed class System.Runtime.InteropServices.Marshal has a method GetObjectForNativeVariant that you can use for converting such "pointers" to objects. However this method does not handle all PropVariant types (for example VT_FILETIME), so for these cases I added my GetObjectForNativeVariant method to this translation.

7-Zip works with files through its own interfaces, so if you want to open file on disk, or in memory you need to provide class implement one or more necessary interfaces. Several such wrapper classes are also present in this translation (they are wrap around standard .NET Stream class).

Update (1.2): Most of the complexity related to PropVariant processing is now hidden in special PropVariant structure. And interface methods now return PropVariant instead of IntPtr.

Known Issues

The first and most disappointing issue is that you cannot use 7-Zip DLLs directly. This means that you cannot simply take such DLLs from 7-Zip distribution and use them in your projects. This is because of the incomplete COM interfaces implementations in 7-Zip code. All issues are related to IUnknown.QueryInterface implementation. 7-Zip's QueryInterface does not return IUnknown interface if prompted (this part is most critical for working with COM-interfaces in .NET), and some classes do not return any interface at all!

This is done because 7-Zip code is C++ code and works with pointers, and most functions returns direct pointers to interface implementation. That means that 7-Zip code not use QueryInterface at all. Sad, but .NET works in a different way, and the first access to any interface always goes though QueryInterface and IUnknown.

So if we use DLLs directly we have constant InvalidCastException. So we need to make several changes in 7-Zip code and rebuild DLLs. Or ask Igor Pavlov to include such changes to the 7-Zip code itself

Important Update: Starting from 7-Zip 4.46 alpha Igor did necessary changes in the code. So, from this version forward, you can use format DLLs directly, without applying any patch. Superb!

The second issue is much smaller one. It is related to multi-threading. If you plan to use 7-Zip interfaces only in one stream you have no problem. The problem comes when you try to use one interface in several threads. In this case all threads except the main one (threads where interfaces are created) throw exceptions on any interface method calls. This is because of RCW behavior. RCW is an object that wraps COM-interface in .NET. When you try to use interface in different thread RCW tries to marshal interface and fails (because this implementation does not support ITypeInfo).

Fortunately I've found simple solutions for this. Main interface (IInArchive) returns as IntPtr, and not as RCW object. When you need to access this interface, call System.Runtime.InteropServices.Marshal.GetTypedObjectForIUnknown or any other related method and get RCW object. If you need to use this interface in another thread simple call System.Runtime.InteropServices.Marshal.FinalReleaseComObject (or ReleaseComObject), and create another RCW wrapper around returned IntPtr pointer. Of course in this case you can use interface only in one thread in time, but this is better than using interface only in one thread. And any logic can be easily implemented with correct thread locking.

And the third issue is a well known issue but I think it must be noted here. It appears that .NET runtime does not support COM interfaces inheritance (interfaces marked with the ComImport attribute). This is definitely a .NET bug, but I don't know when Microsoft fixes this bug, or fix if they fix it at all.

There is simple solution to avoid this bug. Inherited interface must be declared as standalone one and first methods must be methods of inherited interfaces in the order of appearance. You can see sample of such "inheritance" in this translation source.

Demo

Due to many requests, I have spend some time and written a little demo program. The demo program lacks proper error checking, lacks different archives support (zip format is hardcoded in source, but can be easily changed), it lacks almost everything, but it has two advantages: it's simple, and it works.

The demo has only two modes, the first to list all files in archive, and the second is to extract a single file from the archive. I think that this is enough to understand how to use 7-zip interfaces and how to create something more complex.

If you want to run demo, don't forget to put 7z.dll (can be found on official 7-zip site) to the executable folder with executable.

"COM-like" interfaces! This is one reason technologies like COM and .NET came about, to turn messy lone wolf C++ programmers like Pavlov into the conditioned dog. Of course Pavlov probably doesn't give a rat's ass about any particular platform, so is happy as a clam. What other creatures need mentioning? Mean uncle Ivan perhaps.

You said multithreading could be an issue. I needed a Stream implementation for reading and since the extractor uses callback instead of allow single block readings i have implemented a blocking thread that holds the extraction until i want to read-it. The Stream is read-only and i can't seek it back, that enough for me...

The problem is at a certain point the svchost simply hangs and my application fails without any exception, i have discarded any synchronization issues between the threads, is it possible the COM management in C# could be screwing things up?

Hi All.
I can extract ZIP or RAR files by this demo project, it works.
I must extract file.DAT (7zip shows, that this file archive is type: Z)
So I changed code line to:
IInArchive Archive = Format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(KnownSevenZipFormat.Z));
When I try to list archived files from file.DAT, I got: 0.
The problem is:
Archive.GetProperty(I, ItemPropId.kpidPath, ref Name);
or
Console.WriteLine(Name.GetObject());

Public Overridable Sub Seek(ByVal offset As Long, ByVal seekOrigin As UInteger, ByVal newPosition As IntPtr) Implements IInStream.Seek
Dim Position As Long
'Position = CUInt(BaseStream.Seek(offset, DirectCast(seekOrigin, SeekOrigin)))
Position = CUInt(BaseStream.Seek(offset, seekOrigin))
If newPosition <> IntPtr.Zero Then
Marshal.WriteInt64(newPosition, Position)
End If
End Sub
End Class

Public Overridable Sub Seek(ByVal offset As Long, ByVal seekOrigin As UInteger, ByVal newPosition As IntPtr)
Dim Position As Long
'Position = CUInt(BaseStream.Seek(offset, DirectCast(seekOrigin, SeekOrigin)))
Position = CUInt(BaseStream.Seek(offset, seekOrigin))
If newPosition <> IntPtr.Zero Then
Marshal.WriteInt64(newPosition, Position)
End If
End Sub
End Class

..........................................................

but it does not work. can you help me convert C# code into vb code ?
thanks in advance....

You can also try ItemPropId.kpidName to get name. But in simple archive formats like bzip, z and partially gzip, file name is not stored inside archive, so you must reconstruct stored name from the archive name itself (in your case tgz1.tgz => tgz1.tar).

Could someone give me a hint or provide a sample code showing how a password protected archive can be extracted using this library?

Thanks

-- edit --

I found the solution. ICrypto... interface need to be implemented inside ArchiveExtractCallback class. I was doing it exactly the same and it didn't work. Finally found I got another bug which prevented me to decompress.

could you please link me to the code you used to implement password protected compression? It has been 3 years since you post this message I hope you have solved the issue.... Let me know how you did that... If possible please build step-by-step tutorial to use open source 7zip.DLL in VC++ 2010 MFC Application.... Thank you...

First, thanks for that piece of work, it was very helpful! I am using the 2.0 version from the nomad homepage.

I understand basic extracting and creation of archive, that works wonderful. But now I am trying to do two things, which i just do not know how to do correctly:

1.) "Store" files in archive, so that they are not compressed, while creating a ZIP Archive

2.) Encrypt the files with a password

As far as i understand, both things are possible using the ISetProperties. I looked into the 7zip source code, and as far as i could understand, there input of this is an array of names, and array of propvalues, and a count.

The current ISetProperties takes as second parameter an IntPtr - and i do not know how to convert that to an array. I tried to change it to an array of AsAny, which does not work either (Exception when you call the function), and then i tried an Array of I4. This would call, but do nothing.

My call was something like this:
(outArchive as ISetProperties).SetProperties(new string[]{"x"}, new int[]{0},1);

But that does not change anything. Maybe I misunderstood the SetProperties as well. The 7z.exe call i wanted to simulate was "7za a -tZIP -mx=0 test.zip directorywithfiles".

I made a sample *.7z archive (with LZMA compression) using the installed 7Zip tools, then I built your 7Zip interface library and copied 7z.dll from the installation folder into the project Debug output directory and ran the program.

hi, how can I extract all the files in the 7zip file??
i tried to use the sample, but extract only the "0" file, I checekd a compressed file with 4 files, if I read the list, (using the l parameter in the sample ) reads correctly the 4 files, but when I extract, if I use 0 as filenumber extracts correctly the 0 file, but if I use 1 or any other filenumber ( in my case 0, 1, 2, 3 ) nothing will be extracted... the function archive.extract( ... returns 0 if is ok, and a negative number if fails...
does anybody help me?

I am using the version 2.0 from the authors homepage, but i did not experience that problem. I am using a "for" loop to extract all files, and this worked without problems. Could it be that you have an error in the filename you are extracting to? the source code in the sample did not include the folder to extract to, so the files would go the the programs current directory, whatever that is.

I am using c# wrapper of 7Zip.dll.
I want to recognize the file types of the provided archive as an input. Suppose if i wish to extract a zip file, i want to identify it through code that its type is zip. How could i do that in code.

I have one more problem in using c# wrapper of 7Zip.dll.
I need to specify my custom destination folder for the extracted files of archive.
Currently it decompresses all the files in the \bin\debug\ folder and i am not able to specify its custom destination path.

I went through the source code, but I still have no idea how to use it in my project(sorry, because I am a C# beginer). can somebody tell me how to use it? e.g. in the winform, I just need to specify a zip filename(.zip or .rar) and click a button, then the file can be decompression.

It is relatively easy. Just implement IArchiveOpenVolumeCallback with IArchiveOpenCallback. 7z.dll will call GetProperty method with ItemPropId.kpidName, return archive name. Then 7z.dll calls GetStream method and give you archive name, you must provide stream for corresponding volume (or volumes, if there is several).

I had a look at various other source (7zipsharp -> no impl, 7zip itself-> did not help) how those projects implement the iopenarchive volume callback and what to do in the methods GetProperty and GetStream, but I had no luck to get it working.

Maybe I am trying to do things harder than needed and simply don't see it

Could you give me a tip or maybe add the multi volume archive support to your sample code, please? No high end implementation, just to see what these methods expect.
This may help others, too.

Hello everyone. I have finished packing support, and even more, I've spent some time, and demo was updated with simple packing support, so you can find basic using principles of IOutArchive interface.
Sadly, but I did not found a way to update this article on CodeProject. And right now article is updated only on my site (http://dev.nomad-net.info/articles/sevenzipinterface[^]).

P.S. Sorry that update was taken so much time.
P.P.S. Article will be updated as soon as I find way to do this.