Click here to Skip to main content
15,880,651 members
Articles / Programming Languages / XML

Zip/Unzip using the java.util.zip .NET namespace and more

Rate me:
Please Sign up or sign in to vote.
4.49/5 (17 votes)
12 Feb 2013CPOL5 min read 162.1K   3K   70  
Zip/Unzip using java.util.zip from managed code.
/*
 * CPZipStripper 1.0
 * Written by Nishant Sivakumar [http://blog.voidnish.com] 
 * CPZipStripper 2.0
 * Written by Decebal Mihailescu [http://www.codeproject.com/script/articles/list_articles.asp?userid=634640]
*/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Xml;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
//using ICSharpCode.SharpZipLib.Zip; replaced by java.util.zip
using System.Collections.Generic;
using Microsoft.Win32;
using java.util.zip;
using System.Reflection;
using OUTLOOK = Microsoft.Office.Interop.Outlook;

namespace CPZipStripper
{
    using System.Text.RegularExpressions;

    delegate bool IsFileStrippableDelegate(string fname);
    enum Behaviour
    {
        Strip, NoStrip, Ask
    }
    internal class MainForm : System.Windows.Forms.Form
    {
        internal static readonly Regex _emailRegEx =
        new Regex(@"^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$");


        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(
            IntPtr hWnd, bool bRevert);

        [DllImport("user32.dll")]
        private static extern bool AppendMenu(
            IntPtr hMenu, Int32 wFlags, Int32 wIDNewItem,
            string lpNewItem);

        public const Int32 WM_SYSCOMMAND = 0x112;
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1705:LongAcronymsShouldBePascalCased", MessageId = "Member")]
        public const Int32 MF_SEPARATOR = 0x800;
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
        public const Int32 MF_STRING = 0x0;
        public const Int32 IDM_ABOUT = 5000;

        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.Panel panel2;
        private System.Windows.Forms.CheckedListBox CheckedListBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button BtnConfig;
        private System.Windows.Forms.Button BtnRefresh;
        private System.Windows.Forms.Button BtnExit;
        private System.Windows.Forms.Button BtnStrip;
        private System.Windows.Forms.StatusBar statusBar1;
        private System.Windows.Forms.ToolTip MainToolTip;
        private DataSet _dataSet;
        private Button BtnZip;
        private FolderBrowserDialog zipfolderBrowserDialog;
        private System.ComponentModel.IContainer components;
        static private string m_zipFolder;
        static private sbyte[] _buffer = new sbyte[2048];


        internal delegate void AboutHandler();
        //Nish's delegates
        private delegate void DroppedFileHandler(string s, IsFileStrippableDelegate isStripable);

        //Nish's member variables
        static private List<string> m_extensions = new List<string>();
        static private string m_curfile = "";


        internal static readonly string cfgxmlpath = Assembly.GetExecutingAssembly().Location + ".xml";

        public static readonly string strErrXmlFile =
            "Configuration file " + cfgxmlpath + " could not be found " +
            "in the executable's directory.";
        private Button BtnUnZip;
        public static string strErrXmlFileTitle = "Error - Missing Config file!";
        private Button BtnEmail;
        static internal Behaviour _behaviour = Behaviour.Ask;
        public MainForm()
        {

            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //

            MainToolTip.SetToolTip(BtnZip, "Zip Files in the folder");
            MainToolTip.SetToolTip(BtnExit, "Close the program");
            MainToolTip.SetToolTip(BtnConfig, "Open config XML in your XML editor");
            MainToolTip.SetToolTip(BtnRefresh, "Refresh the list for deletion");
            MainToolTip.SetToolTip(BtnEmail, "Email this thip to recepients in the list");
            MainToolTip.SetToolTip(BtnUnZip, "UnZip Files in the folder");
            MainToolTip.SetToolTip(BtnExit, "Close the Application");
            MainToolTip.SetToolTip(CheckedListBox1, "List of files in zip file, checked items will be stripped");
            MainToolTip.SetToolTip(panel1, "Drag and drop any zip file into this window to strip it off unwanted files");
            MainToolTip.SetToolTip(panel2, "Drag and drop any zip file into this window to strip it off unwanted files");
            MainToolTip.SetToolTip(label1, "Drag and drop any zip file into this window to strip it off unwanted files");
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            if (_outLookApp != null)
                Marshal.FinalReleaseComObject(_outLookApp);
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.panel1 = new System.Windows.Forms.Panel();
            this.BtnStrip = new System.Windows.Forms.Button();
            this.BtnExit = new System.Windows.Forms.Button();
            this.BtnUnZip = new System.Windows.Forms.Button();
            this.BtnZip = new System.Windows.Forms.Button();
            this.BtnEmail = new System.Windows.Forms.Button();
            this.BtnRefresh = new System.Windows.Forms.Button();
            this.BtnConfig = new System.Windows.Forms.Button();
            this.panel2 = new System.Windows.Forms.Panel();
            this.CheckedListBox1 = new System.Windows.Forms.CheckedListBox();
            this.label1 = new System.Windows.Forms.Label();
            this.statusBar1 = new System.Windows.Forms.StatusBar();
            this.MainToolTip = new System.Windows.Forms.ToolTip(this.components);
            this._dataSet = new System.Data.DataSet();
            this.zipfolderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
            this.panel1.SuspendLayout();
            this.panel2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this._dataSet)).BeginInit();
            this.SuspendLayout();
            // 
            // panel1
            // 
            this.panel1.Controls.Add(this.BtnStrip);
            this.panel1.Controls.Add(this.BtnExit);
            this.panel1.Controls.Add(this.BtnUnZip);
            this.panel1.Controls.Add(this.BtnZip);
            this.panel1.Controls.Add(this.BtnEmail);
            this.panel1.Controls.Add(this.BtnRefresh);
            this.panel1.Controls.Add(this.BtnConfig);
            this.panel1.Dock = System.Windows.Forms.DockStyle.Left;
            this.panel1.Location = new System.Drawing.Point(0, 24);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(224, 272);
            this.panel1.TabIndex = 0;
            // 
            // BtnStrip
            // 
            this.BtnStrip.Enabled = false;
            this.BtnStrip.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.BtnStrip.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BtnStrip.Location = new System.Drawing.Point(25, 80);
            this.BtnStrip.Name = "BtnStrip";
            this.BtnStrip.Size = new System.Drawing.Size(168, 34);
            this.BtnStrip.TabIndex = 3;
            this.BtnStrip.Text = "Strip Unwanted files";
            this.BtnStrip.Click += new System.EventHandler(this.BtnStrip_Click);
            // 
            // BtnExit
            // 
            this.BtnExit.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.BtnExit.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BtnExit.Location = new System.Drawing.Point(25, 237);
            this.BtnExit.Name = "BtnExit";
            this.BtnExit.Size = new System.Drawing.Size(168, 32);
            this.BtnExit.TabIndex = 4;
            this.BtnExit.Text = "Exit Program";
            this.BtnExit.Click += new System.EventHandler(this.BtnExit_Click);
            // 
            // BtnUnZip
            // 
            this.BtnUnZip.Enabled = false;
            this.BtnUnZip.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.BtnUnZip.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BtnUnZip.Location = new System.Drawing.Point(25, 198);
            this.BtnUnZip.Name = "BtnUnZip";
            this.BtnUnZip.Size = new System.Drawing.Size(168, 32);
            this.BtnUnZip.TabIndex = 2;
            this.BtnUnZip.Text = "&UnZip into Folder...";
            this.BtnUnZip.Click += new System.EventHandler(this.btnUnZip_Click);
            // 
            // BtnZip
            // 
            this.BtnZip.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.BtnZip.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BtnZip.Location = new System.Drawing.Point(25, 159);
            this.BtnZip.Name = "BtnZip";
            this.BtnZip.Size = new System.Drawing.Size(168, 32);
            this.BtnZip.TabIndex = 2;
            this.BtnZip.Text = "&Zip Folder...";
            this.MainToolTip.SetToolTip(this.BtnZip, "Zip Folder");
            this.BtnZip.Click += new System.EventHandler(this.BtnZip_Click);
            // 
            // BtnEmail
            // 
            this.BtnEmail.Enabled = false;
            this.BtnEmail.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.BtnEmail.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BtnEmail.Location = new System.Drawing.Point(25, 120);
            this.BtnEmail.Name = "BtnEmail";
            this.BtnEmail.Size = new System.Drawing.Size(168, 32);
            this.BtnEmail.TabIndex = 2;
            this.BtnEmail.Text = "&Email current zip";
            this.BtnEmail.Click += new System.EventHandler(this.BtnEmail_Click);
            // 
            // BtnRefresh
            // 
            this.BtnRefresh.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.BtnRefresh.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BtnRefresh.Location = new System.Drawing.Point(25, 41);
            this.BtnRefresh.Name = "BtnRefresh";
            this.BtnRefresh.Size = new System.Drawing.Size(168, 32);
            this.BtnRefresh.TabIndex = 2;
            this.BtnRefresh.Text = "Refresh CheckedListBox";
            this.BtnRefresh.Click += new System.EventHandler(this.BtnRefresh_Click);
            // 
            // BtnConfig
            // 
            this.BtnConfig.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.BtnConfig.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.BtnConfig.Location = new System.Drawing.Point(25, 2);
            this.BtnConfig.Name = "BtnConfig";
            this.BtnConfig.Size = new System.Drawing.Size(168, 32);
            this.BtnConfig.TabIndex = 1;
            this.BtnConfig.Text = "Modify Configuration";
            this.BtnConfig.Click += new System.EventHandler(this.BtnConfig_Click);
            // 
            // panel2
            // 
            this.panel2.Controls.Add(this.CheckedListBox1);
            this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel2.Location = new System.Drawing.Point(224, 24);
            this.panel2.Name = "panel2";
            this.panel2.Padding = new System.Windows.Forms.Padding(4);
            this.panel2.Size = new System.Drawing.Size(482, 272);
            this.panel2.TabIndex = 1;
            // 
            // CheckedListBox1
            // 
            this.CheckedListBox1.CheckOnClick = true;
            this.CheckedListBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.CheckedListBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.CheckedListBox1.HorizontalScrollbar = true;
            this.CheckedListBox1.Location = new System.Drawing.Point(4, 4);
            this.CheckedListBox1.Name = "CheckedListBox1";
            this.CheckedListBox1.Size = new System.Drawing.Size(474, 256);
            this.CheckedListBox1.Sorted = true;
            this.CheckedListBox1.TabIndex = 0;
            this.CheckedListBox1.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.CheckedListBox1_ItemCheck);
            // 
            // label1
            // 
            this.label1.BackColor = System.Drawing.SystemColors.ControlDark;
            this.label1.Dock = System.Windows.Forms.DockStyle.Top;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.ForeColor = System.Drawing.Color.Blue;
            this.label1.Location = new System.Drawing.Point(0, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(706, 24);
            this.label1.TabIndex = 2;
            this.label1.Text = "Drag and drop any zip file or folder into this window to strip it off unwanted fi" +
                "les";
            // 
            // statusBar1
            // 
            this.statusBar1.Location = new System.Drawing.Point(0, 296);
            this.statusBar1.Name = "statusBar1";
            this.statusBar1.Size = new System.Drawing.Size(706, 22);
            this.statusBar1.TabIndex = 3;
            this.statusBar1.Text = "No file is currently open";
            // 
            // _dataSet
            // 
            this._dataSet.DataSetName = "NewDataSet";
            // 
            // zipfolderBrowserDialog
            // 
            this.zipfolderBrowserDialog.ShowNewFolderButton = false;
            // 
            // MainForm
            // 
            this.AllowDrop = true;
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(706, 318);
            this.Controls.Add(this.panel2);
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.statusBar1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MinimumSize = new System.Drawing.Size(714, 352);
            this.Name = "MainForm";
            this.Text = "CodeProject Zip Stripper";
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.DragDrop += new System.Windows.Forms.DragEventHandler(this.MainForm_DragDrop);
            this.DragEnter += new System.Windows.Forms.DragEventHandler(this.MainForm_DragEnter);
            this.panel1.ResumeLayout(false);
            this.panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this._dataSet)).EndInit();
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (File.Exists(cfgxmlpath))
                Application.Run(new MainForm());
            else
                MessageBox.Show(strErrXmlFile, strErrXmlFileTitle);
        }

        private void MainForm_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            Array arr = (Array)e.Data.GetData(DataFormats.FileDrop);
            if (arr != null)
            {

                this.Invoke(new DroppedFileHandler(ProcessFileSystemEntry),
                    new object[2] { arr.GetValue(0).ToString(), new IsFileStrippableDelegate(IsFileStrippable) });
            }
        }

        private void MainForm_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ?
                DragDropEffects.Copy : DragDropEffects.None;
        }

        private void ShowFilteredZip(string strFile, IsFileStrippableDelegate isStripabale)
        {
            List<string> list = null;
            bool bContainsTrash = false;
            try
            {

                Splash.CreateSplash(this);
                Splash.SetSplash("Show content", 10);

                this.Cursor = Cursors.WaitCursor;
                list = ZipUtility.GetZipFileNames(strFile);
                bContainsTrash = false;
                CheckedListBox1.Items.Clear();
                foreach (string name in list)
                {
                    System.Windows.Forms.Application.DoEvents();
                    statusBar1.Text = name;
                    bool bistrash = isStripabale != null && isStripabale(name);
                    CheckedListBox1.Items.Add(name, bistrash);
                    if (bistrash)
                        bContainsTrash = true;
                }

                m_curfile = strFile;
                MainToolTip.SetToolTip(BtnStrip, bContainsTrash ? "Strip zip off unwanted files" : string.Empty);
            }
            catch (Exception ex)
            {
                Splash.DestroySplash();
                Application.DoEvents();
                MessageBox.Show(this, ex.Message, "Error in " + strFile, MessageBoxButtons.OK, MessageBoxIcon.Error);
                m_curfile = string.Empty;
                CheckedListBox1.Items.Clear();
            }
            finally
            {
                this.Cursor = Cursors.Default;
                BtnUnZip.Enabled = m_curfile.Length > 0;
                BtnStrip.Enabled = m_curfile.Length > 0 && bContainsTrash;
                statusBar1.Text = GetFileInfo();// m_curfile;
                BtnEmail.Text = "&Email " + Path.GetFileName(m_curfile);
                BtnEmail.Enabled = _outLookApp != null;
                Splash.DestroySplash();
                Application.DoEvents();
            }
        }
        string GetFileInfo()
        {
            FileInfo fi = new FileInfo(m_curfile);

            long len = fi.Length;
            if (len < 1024)
                return string.Format("{0} size {1} bytes", m_curfile, len);
            else
                return string.Format("{0} size {1:###,###,###} KB", m_curfile, len / 1024);
        }
        OUTLOOK.ApplicationClass _outLookApp;
        private void MainForm_Load(object sender, System.EventArgs e)
        {
            ReadConfig();
            string[] argv = Environment.GetCommandLineArgs();
            if (argv.Length == 2)
            {
                //if (!System.Diagnostics.Debugger.IsAttached)
                //{
                //    System.Diagnostics.Debugger.Launch();
                //}
                ProcessFileSystemEntry(argv[1], new IsFileStrippableDelegate(IsFileStrippable));
            }
            Version v = Assembly.GetExecutingAssembly().GetName().Version;
            Text += string.Format(" {0}.{1}", v.Major, v.Minor);
            AboutUtil.About.InitSysMenu(this);

            try
            {
                _outLookApp = new OUTLOOK.ApplicationClass();
            }
            catch
            {
                _outLookApp = null;
            }
            finally
            {
                BtnEmail.Enabled = !string.IsNullOrEmpty(m_curfile) && _outLookApp != null;
            }
            AddContextMenuItem(".zip", "ZipStrip", "Open with &ZipStrip", "\"" + Application.ExecutablePath + "\" \"%1\"");
        }

        private void ProcessFileSystemEntry(string Entry, IsFileStrippableDelegate IsStipable)//new IsFileStrippableDelegate(IsFileStrippable)
        {
            try
            {

                if (Directory.Exists(Entry))
                {//zip this folder

                    string strNewFile = null;
                    try
                    {

                        Cursor = Cursors.WaitCursor;
                        m_zipFolder = Entry;
                        strNewFile = m_zipFolder + ".zip";
                        string fileName = Path.GetFileName(strNewFile);
                        strNewFile = Path.GetDirectoryName(strNewFile) + @"\" + fileName;
                        IsFileStrippableDelegate strip = null;
                        switch (_behaviour)
                        {
                            case Behaviour.Strip:
                                strip = new IsFileStrippableDelegate(IsFileStrippable);
                                break;
                            case Behaviour.Ask:
                                if (MessageBox.Show(this, "Do you want to strip before creating the archive?",
                                    "Remove unwanted files", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                    strip = new IsFileStrippableDelegate(IsFileStrippable);
                                break;
                        }
                        Splash.CreateSplash(this);
                        Splash.SetSplash("Zipping folder " + Entry, 100);
                        ZipUtility.CreateZipFromFolder(m_zipFolder, strip);
                        m_curfile = strNewFile;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this,
                            "unable to zip " + strNewFile + "\n" + ex.Message,
                            "Error : Unexpected zip file format!",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                        m_curfile = string.Empty;
                    }
                    finally
                    {

                        if (m_curfile != null && m_curfile.Length > 0)
                            ShowFilteredZip(m_curfile, IsStipable);
                        Cursor = Cursors.Default;
                    }
                }
                else if (File.Exists(Entry))
                {
                    Splash.CreateSplash(this);
                    Splash.SetSplash("Gets zip content", 10);
                    ShowFilteredZip(Entry, new IsFileStrippableDelegate(IsFileStrippable));
                }
            }
            finally
            {
                Splash.DestroySplash();
            }

        }

        private bool IsFileStrippable(string fname)
        {
            bool ret = false;
            string path = null, name = null, ext = null;
            SplitString(fname.ToLower(), ref path, ref name, ref ext);
            //WildCharTextUtility search = new WildCharTextUtility();
            //try the simple classic extension
            if (m_extensions.Contains("." + ext.ToLower()))
                return true;
            //try the wildchar search
            foreach (string pat in m_extensions)
            {
                //statusBar1.Text = fname + " against " + pat;
                if (pat.IndexOfAny("*?".ToCharArray()) < 0)
                {//check for a complex extension
                    int index = fname.LastIndexOf(pat);
                    if (index >= 0 && (index + pat.Length == fname.Length))
                        return true;
                    continue;//already checked above
                }
                string pattern = pat;
                if (WildCharTextUtility.IsPatternMatch(ref fname, ref pattern, false))
                    return true;
            }
            foreach (DataRow row in _dataSet.Tables[Config._FolderTable].Rows)
            {
                string pathstr = row[Config._PathField].ToString().ToLower();
                if (pathstr.Length > 0)//no empty mask
                {
                    if (("\\" + path).IndexOf("\\" + pathstr + "\\") != -1)
                    {
                        return true;
                    }

                }
            }
            foreach (DataRow row in _dataSet.Tables[Config._FileTable].Rows)
            {
                string val = row[Config._FileField].ToString();
                if (string.Compare(val, name + "." + ext, true) == 0)
                    return true;
            }
            return ret;
        }

        static private void SplitString(string fname, ref string path,
            ref string name, ref string ext)
        {
            path = name = ext = "";
            if (fname.Length != 0)
            {
                int slashpos = fname.LastIndexOf("\\");
                if (slashpos != -1)
                {
                    path = fname.Substring(0, slashpos + 1);
                }
                name = fname.Substring(path.Length);
                int dotpos = name.LastIndexOf(".");
                if (dotpos != -1)
                {
                    ext = name.Substring(dotpos + 1);
                    name = name.Substring(0, dotpos);
                }
            }
            path = path.ToLower();
            name = name.ToLower();
            ext = ext.ToLower();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        internal void ReadConfig()
        {
            try
            {
                XmlDocument xd = new XmlDocument();
                xd.Load(cfgxmlpath);
                try
                {

                    XmlNode behaviour = xd["configuration"]["Behaviour"];
                    _behaviour = (Behaviour)Enum.Parse(typeof(Behaviour), behaviour.Attributes["value"].InnerText);
                }
                catch
                {
                    _behaviour = Behaviour.Ask;
                }
                //use the data set
                m_extensions.Clear();
                _dataSet = new DataSet("configuration");
                _dataSet.Locale = System.Globalization.CultureInfo.CurrentUICulture;
                DataTable maskTable = new DataTable(Config._maskTable);
                DataColumn maskCol = new DataColumn(Config._maskField,
                    Type.GetType("System.String"), null, MappingType.Attribute);
                maskTable.Columns.Add(maskCol);
                _dataSet.Tables.Add(maskTable);
                _dataSet.Tables[Config._maskTable].ReadXml(MainForm.cfgxmlpath);
                for (int i = 0; i < _dataSet.Tables[Config._maskTable].Rows.Count; i++)
                {
                    DataRow row = _dataSet.Tables[Config._maskTable].Rows[i];
                    string val = row[Config._maskField].ToString().ToLower();
                    if (val.Length > 0)//no empty mask
                    {
                        if (val.StartsWith("*."))
                        {
                            string rest = val.Substring(1);
                            if (rest.IndexOfAny("*?".ToCharArray()) >= 0)
                            {
                                if (!m_extensions.Contains(val))
                                    m_extensions.Add(val);
                            }
                            else// for performance reasons use the equivalent
                            {
                                if (!m_extensions.Contains(rest))
                                    m_extensions.Add(rest);
                            }
                        }
                        else
                            if (!m_extensions.Contains(val))
                                m_extensions.Add(val);
                    }
                    else
                    {   //don't show empty rows
                        row.Delete();
                    }
                }

                DataTable folderTable = new DataTable(Config._FolderTable);
                DataColumn fieldCol = new DataColumn(Config._PathField,
                    Type.GetType("System.String"), null, MappingType.Attribute);
                folderTable.Columns.Add(fieldCol);
                _dataSet.Tables.Add(folderTable);
                _dataSet.Tables[Config._FolderTable].ReadXml(MainForm.cfgxmlpath);
                for (int i = 0; i < _dataSet.Tables[Config._FolderTable].Rows.Count; i++)
                {
                    DataRow row = _dataSet.Tables[Config._FolderTable].Rows[i];
                    string val = row[Config._PathField].ToString().ToLower();
                    if (val.Length == 0)//no empty mask
                        row.Delete();
                }

                DataTable fileTable = new DataTable(Config._FileTable);
                DataColumn fileCol = new DataColumn(Config._FileField,
                    Type.GetType("System.String"), null, MappingType.Attribute);
                fileTable.Columns.Add(fileCol);
                _dataSet.Tables.Add(fileTable);
                _dataSet.Tables[Config._FileTable].ReadXml(MainForm.cfgxmlpath);
                for (int i = 0; i < _dataSet.Tables[Config._FileTable].Rows.Count; i++)
                {
                    DataRow row = _dataSet.Tables[Config._FileTable].Rows[i];
                    string val = row[Config._FileField].ToString().ToLower();
                    if (val.Length == 0)//no empty mask
                        row.Delete();
                }

                DataTable EmailTable = new DataTable(Config._EmailTable);
                DataColumn EmailCol = new DataColumn(Config._EmailField,
                    Type.GetType("System.String"), null, MappingType.Attribute);
                EmailTable.Columns.Add(EmailCol);
                _dataSet.Tables.Add(EmailTable);
                _dataSet.Tables[Config._EmailTable].ReadXml(MainForm.cfgxmlpath);
                for (int i = 0; i < _dataSet.Tables[Config._EmailTable].Rows.Count; i++)
                {
                    DataRow row = _dataSet.Tables[Config._EmailTable].Rows[i];
                    string val = row[Config._EmailField].ToString();
                    //   (".+@.+\\.[a-z]+");
                    if (val.Length == 0 || !_emailRegEx.IsMatch(val))//no empty or bad email
                        row.Delete();
                }
                _dataSet.AcceptChanges();


            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error reading " + cfgxmlpath,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnExit_Click(object sender,
            System.EventArgs e)
        {
            Close();
        }

        private void BtnRefresh_Click(object sender,
            System.EventArgs e)
        {
            if (m_curfile.Length > 0)
            {
                try
                {
                    Cursor = Cursors.WaitCursor;
                    ReadConfig();
                    ShowFilteredZip(m_curfile, new IsFileStrippableDelegate(IsFileStrippable));
                }
                finally
                {
                    Cursor = Cursors.Default;
                }
            }
        }

        private void BtnConfig_Click(object sender,
            System.EventArgs e)
        {
            Config dlg = new Config();
            dlg.Owner = this;
            dlg._dataSet = _dataSet;
            dlg.ShowDialog(this);
            dlg.Dispose();
            return;
        }

        private void BtnStrip_Click(object sender, System.EventArgs e)
        {
            if (m_curfile == null || m_curfile.Length == 0)
                return;
            List<string> trashList = null;
            try
            {
                Cursor = Cursors.WaitCursor;
                CheckedListBox.CheckedItemCollection col = CheckedListBox1.CheckedItems;
                trashList = new List<string>(col.Count);
                for (int x = 0; x < CheckedListBox1.CheckedItems.Count; x++)
                {
                    trashList.Add(col[x].ToString());
                }

                Splash.CreateSplash(this);
                Splash.SetSplash("Stripping zip " + m_curfile, 100);

                ZipUtility.StripZip(m_curfile, trashList);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this,
                    "unable to zip/unzip: " + m_curfile +
                    "\ncould be password protected\n" + ex.Message,
                    "Error : Unexpected zip file format!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (trashList != null)
                    trashList.Clear();
                ShowFilteredZip(m_curfile, null);
                Cursor = Cursors.Default;
                Splash.DestroySplash();
            }
        }

        private static bool AddContextMenuItem(string Extension,
            string MenuName, string MenuDescription, string MenuCommand)
        {
            bool ret = false;
            RegistryKey regmenu = null;
            RegistryKey regcmd = null;
            try
            {
                RegistryKey rkey = Registry.ClassesRoot.OpenSubKey(Extension);
                if (rkey != null)
                {
                    string extstring = rkey.GetValue("").ToString();
                    rkey.Close();
                    if (extstring != null)
                    {
                        if (extstring.Length > 0)
                        {
                            rkey = Registry.ClassesRoot.OpenSubKey(extstring, true);
                            if (rkey != null)
                            {
                                string strkey = "shell\\" + MenuName + "\\command";
                                RegistryKey subky = rkey.CreateSubKey(strkey);
                                if (subky != null)
                                {
                                    subky.SetValue("", MenuCommand);
                                    subky.Close();
                                    subky = rkey.OpenSubKey("shell\\" + MenuName, true);
                                    if (subky != null)
                                    {
                                        subky.SetValue("", MenuDescription);
                                        subky.Close();
                                    }
                                    ret = true;
                                }
                                rkey.Close();
                            }
                        }
                    }
                }
                regmenu = Registry.ClassesRoot.CreateSubKey(@"Folder\shell\NewMenuOption");
                if (regmenu != null)
                    regmenu.SetValue("", MenuName + " &Folder");
                regcmd = Registry.ClassesRoot.CreateSubKey(@"Folder\shell\NewMenuOption\command");
                if (regcmd != null)
                    regcmd.SetValue("", MenuCommand);
            }
            catch
            {
                ret = false;
            }
            finally
            {
                if (regmenu != null)
                    regmenu.Close();
                if (regcmd != null)
                    regcmd.Close();
            }


            return ret;
        }

        private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            int cnt = 0;
            for (int i = 0; i < CheckedListBox1.Items.Count; i++)
            {
                if (e.Index != i)
                {
                    if (CheckedListBox1.GetItemChecked(i))
                        cnt++;
                }
                else
                {
                    if (!CheckedListBox1.GetItemChecked(i))
                        cnt++;
                }
            }
            BtnStrip.Enabled = cnt > 0;
        }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.MessageBox.Show(System.Windows.Forms.IWin32Window,System.String,System.String,System.Windows.Forms.MessageBoxButtons,System.Windows.Forms.MessageBoxIcon)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.MessageBox.Show(System.Windows.Forms.IWin32Window,System.String,System.String,System.Windows.Forms.MessageBoxButtons)")]
        private void BtnZip_Click(object sender, EventArgs e)
        {
            string strNewFile = null;

            try
            {
                XmlDocument xd = new XmlDocument();
                xd.Load(cfgxmlpath);
                XmlNode lastFolderpath = xd["configuration"]["LastUsedFolder"];
                if (lastFolderpath != null)
                {
                    zipfolderBrowserDialog.SelectedPath = lastFolderpath.Attributes["value"].InnerText;
                }
                else
                    zipfolderBrowserDialog.SelectedPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (DialogResult.OK == zipfolderBrowserDialog.ShowDialog(this))
                {
                    Cursor = Cursors.WaitCursor;
                    m_zipFolder = zipfolderBrowserDialog.SelectedPath;
                    if (lastFolderpath != null)
                        lastFolderpath.Attributes["value"].InnerText = m_zipFolder;
                    xd.Save(MainForm.cfgxmlpath);
                    strNewFile = m_zipFolder + ".zip";
                    string fileName = Path.GetFileName(strNewFile);
                    strNewFile = Path.GetDirectoryName(strNewFile) + @"\" + fileName;
                    IsFileStrippableDelegate strip = null;
                    switch (_behaviour)
                    {
                        case Behaviour.Strip:
                            strip = new IsFileStrippableDelegate(IsFileStrippable);
                            break;
                        case Behaviour.Ask:
                            if (MessageBox.Show(this, "Do you want to strip before creating the archive?",
                                "Remove unwanted files", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                strip = new IsFileStrippableDelegate(IsFileStrippable);
                            break;
                    }
                    Splash.CreateSplash(this);
                    Splash.SetSplash("Zipping folder" + m_zipFolder, 100);

                    ZipUtility.CreateZipFromFolder(m_zipFolder, strip);
                    m_curfile = strNewFile;
                    this.BtnUnZip.Enabled = true;
                    statusBar1.Text = GetFileInfo();// m_curfile;
                    BtnEmail.Text = "&Email " + Path.GetFileName(m_curfile);
                    BtnEmail.Enabled = _outLookApp != null;

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(this,
                    "unable to zip " + strNewFile + "\n" + ex.Message,
                    "Error : Unexpected zip file format!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (m_curfile != null && m_curfile.Length > 0)
                    ShowFilteredZip(m_curfile, new IsFileStrippableDelegate(IsFileStrippable));
                Cursor = Cursors.Default;
                Splash.DestroySplash();
            }


        }

        private void btnUnZip_Click(object sender, EventArgs e)
        {

            try
            {
                XmlDocument xd = new XmlDocument();
                xd.Load(cfgxmlpath);
                XmlNode lastFolderpath = xd["configuration"]["LastUsedFolder"];
                if (lastFolderpath != null)
                {
                    zipfolderBrowserDialog.SelectedPath = lastFolderpath.Attributes["value"].InnerText;
                }
                else
                    zipfolderBrowserDialog.SelectedPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                //zipfolderBrowserDialog.SelectedPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (DialogResult.OK == zipfolderBrowserDialog.ShowDialog(this))
                {
                    Cursor = Cursors.WaitCursor;
                    m_zipFolder = zipfolderBrowserDialog.SelectedPath;
                    Splash.CreateSplash(this);
                    Splash.SetSplash("unzipping into " + m_zipFolder, 100);

                    ZipUtility.UnZip(m_curfile, m_zipFolder, null);
                    if (lastFolderpath != null)
                        lastFolderpath.Attributes["value"].InnerText = m_zipFolder;
                    xd.Save(MainForm.cfgxmlpath);

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error : Unexpected zip file format!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (m_curfile != null && m_curfile.Length > 0)
                    ShowFilteredZip(m_curfile, new IsFileStrippableDelegate(IsFileStrippable));
                Cursor = Cursors.Default;
                Splash.DestroySplash();
            }
        }

        private void BtnEmail_Click(object sender, EventArgs e)
        {

            OUTLOOK.MailItem myMail = null;
            StringBuilder sb = new StringBuilder(20);
            EMailForm emailDlg = null;
            try
            {
                emailDlg = new EMailForm(this._dataSet, Path.GetFileName(m_curfile));
                if (emailDlg.ShowDialog(this) == DialogResult.Cancel)
                    return;
                if (emailDlg.Emails.Count == 0)
                {
                    if (MessageBox.Show(this,
                        "You must configure the email list before sending emails.\nor enter a valid email.\nDo you want to do it now?",
                        "No email list", MessageBoxButtons.YesNo) == DialogResult.No)
                        return;
                    else
                    {
                        Config dlg = new Config();
                        dlg.Owner = this;
                        dlg._dataSet = _dataSet;
                        dlg.ShowDialog(this);
                        dlg.Dispose();
                        if (_dataSet.Tables[Config._EmailTable].Rows.Count == 0)
                            return;
                    }
                }

                BtnEmail.Enabled = false;
                BtnEmail.UseWaitCursor = true;
                Application.DoEvents();

                // Create a new MailItem.
                myMail = _outLookApp.CreateItem(OUTLOOK.OlItemType.olMailItem) as OUTLOOK.MailItem;

                foreach (string val in emailDlg.Emails)
                {
                    myMail.Recipients.Add(val);
                    sb.Append(val + ";");
                }
                if (sb.Length > 0)
                    sb.Length -= 1;
                myMail.Subject = m_curfile + " included";

                myMail.Body = "sending attachement " + m_curfile;
                myMail.Attachments.Add(m_curfile, OUTLOOK.OlAttachmentType.olByValue, myMail.Body.Length + 1, m_curfile);

                // Send it!
                if (emailDlg.Emails.Count > 0)
                {
                    myMail.Send();
                    statusBar1.Text = string.Format("Sent {0} to {1}", Path.GetFileName(m_curfile), sb.ToString());
                }
            }
            catch (System.Exception ex)
            {
                statusBar1.Text = string.Format("Fail to send {0} to {1} because {2}", m_curfile, sb.ToString(), ex.Message);
            }
            finally
            {
                emailDlg.Dispose();
                BtnEmail.Enabled = true;
                BtnEmail.UseWaitCursor = false;
                if (myMail != null)
                    Marshal.FinalReleaseComObject(myMail);
                sb.Length = 0;
            }
        }


    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Decebal Mihailescu is a software engineer with interest in .Net, C# and C++.

Comments and Discussions