Opening Jars with C#


Introduction

This article shall describe an approach that may be used to extract Jar files.  Jars are merely files compressed using zip compression; the primary difference between a standard trash zip file and a jar file is that the jar file includes a manifest; also a true jar files can be run as an executable on a machine equipped with the java runtime.  Jars typically contain java class files; if you have some need to extract a jar and view its contents, it is no more difficult to do that than it is to unzip a normal zip file.

Figure 1:  Extracting a Jar File

Since the task of extracting a jar is really the same as it is to extract a zip file, the demo application will rely upon the free SharpZipLib libraries to perform the extraction; these libraries may be downloaded from this location:  http://www.icsharpcode.net/OpenSource/SharpZipLib/

In addition to handling jar and zip files, the library also handles tar, gzip, and bzip2 compression.

The Solution

The solution contains a single project (Jars).  The example is provided in the form of a single Windows Forms project; the project contains a single main form; the references are all in the default configuration with the exception being that the SharpZipLib DLL has been added (first item in the reference list).  Having downloaded the DLL from the www.icsharpcode.net web, the download was installed into the local file system and was adding by using the "Add Reference" dialog's Browse option.  All of the code necessary to drive the application is included in the main form's code file.

Figure 2:  The Solution Explorer Showing the Project

The Code:  Jars - Form1

The Jars project is a Windows Forms project containing a single form.  All UI and code required by the project are contained in the single main form.
The only references added to the project, aside from the defaults, were those necessary to support the use of the SharpZipLib in the project.  The imports, namespace, and class declarations are as follows:

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using ICSharpCode.SharpZipLib.Zip;

using System.IO; 

 

namespace Jars

{

 

    public partial class Form1 : Form

    {

After the class declaration, two private variables are declared;  these variables are used to retain the path to the jar file and the path to the destination folder (where the jar will be unpacked).

        // set variables to hold

        // the paths to the jar file and

        // to destination folder

        private string mSourceJar;

        private string mDestinationFolder;

the next block of code is the default constructor; nothing added there:

        // default constructor

        public Form1()

        {

            InitializeComponent();

        }

The next block of code is used to perform the actual extraction.  The ExtractJar function accepts two arguments, a string value defining the path to the jar file, and a string value defining the path to the destination folder (the location at which the jar will be unpacked).  The method uses the SharpZipLibrary to extract the jar file.  The code in annotated to describe the activity. 

  /// <summary>

        /// Extracts the jar file to a specified

        /// destination folder. 

        /// </summary>

        private void ExtractJar(string pathToJar, string saveFolderPath)

        {

            string jarPath = pathToJar;

            string savePath = saveFolderPath;

 

            try

            {

                // verify the paths are set

                if (!String.IsNullOrEmpty(jarPath) &&

                   !String.IsNullOrEmpty(saveFolderPath))

                {

                    try

                    {

                        // use the SharpZip library FastZip

                        // utilities ExtractZip method to

                        // extract the jar file

                        FastZip fz = new FastZip();

                        fz.ExtractZip(jarPath, saveFolderPath, "");

 

                        // Success at this point, tell the user

                        // we are done.

                        MessageBox.Show("Jar File: " + jarPath + " was

                        extracted to " +

                        saveFolderPath, "Finished");

 

                        // open the destination folder in explorer

                        System.Diagnostics.Process.Start("explorer",

                        saveFolderPath);

                    }

                    catch (Exception ex)

                    {

                        // something went wrong

                        MessageBox.Show(ex.Message, "Extraction Error");

                    }

                }

                else

                {

                    // the paths were not, tell the user to

                    // get with the program

 

                    StringBuilder sb = new StringBuilder();

                    sb.Append("Set the paths to both the jar file and " +

                    Environment.NewLine);

 

                    sb.Append("destination folder before attempting to " +

                    Environment.NewLine);

 

                    sb.Append("to extract a jar file.");

 

                    MessageBox.Show(sb.ToString(), "Unable to Extract");

                }

            }

            catch (Exception ex)

            {

                // something else went wrong

                MessageBox.Show(ex.Message, "Extraction Method Error");

            } 

        }       

The next block of code is used to set the path to the jar file.  This button click event handler is used to display an open file dialog box; the user can use the dialog box to navigate to the location of the jar file and select it.  The selected file name is used to set the mSourceJar string variable to the file path of the jar file; the file path is also displayed in the text box adjacent to the button.

         /// <summary>

        /// Set the path to the Jar File

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnSetJar_Click(object sender, EventArgs e)

        {

            try

            {

                OpenFileDialog1.Title = "Extract JAR";

                OpenFileDialog1.DefaultExt = "jar";

                OpenFileDialog1.Filter = "Jar Files|*.jar";

                OpenFileDialog1.FileName = string.Empty;

                OpenFileDialog1.Multiselect = false;

 

                if (OpenFileDialog1.ShowDialog() == DialogResult.OK)

                {

                    if (OpenFileDialog1.FileName == "")

                    {

                        return;

                    }

 

                    string strExt;

                    strExt =

                    System.IO.Path.GetExtension(OpenFileDialog1.FileName);

                    strExt = strExt.ToUpper();

 

                    if (strExt == ".JAR")

                    {

                        mSourceJar = OpenFileDialog1.FileName;

                        txtJarPath.Text = mSourceJar;

                    }

                    else

                    {

                        MessageBox.Show("The selected file is not a jar",

                        "File Error");

                    }

 

                }

                else

                {

                    MessageBox.Show("File request cancelled by user.",

                    "Cancelled");

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message.ToString(), "Error");

            }

        }

The next section of code is used to set the path to the destination folder.  The destination folder defines the location where the selected jar file will be unpacked.  The button click event handler opens a folder browser dialog which will permit the user to navigate to and/or to create a destination folder.  Once set, the folder browser dialog's selected path property is used to the mDestinationFolder variable and it is also used to display the selected destination folder path using the selected path's value.

        /// <summary>

        /// Set the path to the destination folder

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnDestinationFolder_Click(object sender, EventArgs e)

        {

            try

            {

                folderBrowserDialog1.ShowNewFolderButton = true;

 

                DialogResult result = folderBrowserDialog1.ShowDialog();

                if (result == DialogResult.OK)

                {

                    mDestinationFolder = folderBrowserDialog1.SelectedPath;

                    txtDestinationFolder.Text = mDestinationFolder;

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message, "Error Setting Destination

                Folder");

            }

        }

The last button click event handler is used to call the ExtractJar method.  The click event handler merely evokes the ExtractJar method and passes it the two variables used to contain the source jar file and the destination folder.

        /// <summary>

        /// Use the ExtractJar function to

        /// extract the source jar file into the

        /// destination folder

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnExtract_Click(object sender, EventArgs e)

        {

            ExtractJar(mSourceJar, mDestinationFolder);

        }

That wraps up the description of the code used in this project.

Summary.

This example demonstrates extracting a jar file using SharpZipLib; Jar files are nothing more than zip compressed archives containing some meta data along with (typically) java class files; extracting them is no more difficult than extracting a normal zipped archive; particularly with the assistance of the SharpZipLib.

Up Next
    Ebook Download
    View all
    Learn
    View all