简体   繁体   中英

How can I add a ProgressBar to my SharpZipLib utility in C#

I need to include a progressbar in my project but I'm not sure how to do or how successful call to the method that will be updated. The code where I want to include is the following, thank you very much:

using System;
using System.Collections;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Windows.Forms;
using System.Management;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;


namespace PCCoste
{
    public partial class FormBackup : Form
    {
        private string rutaDestinoCopia;
        private string nombreArchivo;
        private Timer time = new Timer();

        //static NameValueCollection configItems;

        public FormBackup()
        {
            InitializeComponent();
            if (File.Exists("backup.ini"))
            {
                StreamReader sr = new StreamReader("backup.ini");
                rutaDestinoCopia = sr.ReadLine();
                nombreArchivo = sr.ReadLine();
                sr.Close();
                txtRutaDestino.Text = rutaDestinoCopia;
                txtNombreArchivo.Text = nombreArchivo;
            }
        }

        private void botonDestino_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog expArchivos = new FolderBrowserDialog();
            expArchivos.RootFolder = Environment.SpecialFolder.MyComputer;
            expArchivos.ShowNewFolderButton = true;
            expArchivos.Description = "Seleccione unidad o carpeta de destino para realizar la copia de seguridad.";

            if (expArchivos.ShowDialog(this) != DialogResult.Cancel)
            {
                rutaDestinoCopia = expArchivos.SelectedPath;
                txtRutaDestino.Text = rutaDestinoCopia;

            }
        }

        private void botonBackup_Click(object sender, EventArgs e)
        {
            StreamWriter escribeArchivo = new StreamWriter("backup.ini");
            escribeArchivo.WriteLine(txtRutaDestino.Text);
            escribeArchivo.WriteLine(txtNombreArchivo.Text);
            escribeArchivo.Close();
            Zip("C:\\Users\\Andrés\\Desktop\\PCCoste\\PCCoste\\bbdd",
                rutaDestinoCopia + "\\" + nombreArchivo + "-" + DateTime.Now.ToString("ddMMyyyy") + ".zip",
                txtContraseña.Text);
        }

        public static void Zip(string Path, string outPathAndZipFile, string password)
        {
            string OutPath = outPathAndZipFile;
            ArrayList lista = GenerateFileList(Path); // Genera la listade archivos.

            int TrimLength = (Directory.GetParent(Path)).ToString().Length;
            TrimLength += 1; //borra '\'
            FileStream flujoArchivos;
            byte[] obuffer;
            ZipOutputStream ZipStream = new ZipOutputStream(System.IO.File.Create(OutPath)); // creamos el zip
            ZipStream.SetLevel(9); // 9 = nivel de compresión máxima.

            if (password != String.Empty) ZipStream.Password = password;

            ZipEntry ZipEntrada;
            foreach (string archivo in lista) // para cada archivo genera una entrada zip
            {
                ZipEntrada = new ZipEntry(archivo.Remove(0, TrimLength));
                ZipStream.PutNextEntry(ZipEntrada);

                if (!archivo.EndsWith(@"/")) // si el archivo acaba es '/' es que es una carpeta
                {
                    flujoArchivos = File.OpenRead(archivo);
                    obuffer = new byte[flujoArchivos.Length]; // buffer
                    flujoArchivos.Read(obuffer, 0, obuffer.Length);
                    ZipStream.Write(obuffer, 0, obuffer.Length);
                    Console.Write(".");
                    flujoArchivos.Close();
                }
            }
            ZipStream.Finish();
            ZipStream.Close();
            MessageBox.Show("Copia terminada con éxito", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private static ArrayList GenerateFileList(string Dir)
        {
            ArrayList mid = new ArrayList();
            bool Empty = true;
            foreach (string file in Directory.GetFiles(Dir)) // añada cada archivo al directorio
            {
                mid.Add(file);
                Empty = false;
            }

            if (Empty)
            {
                if (Directory.GetDirectories(Dir).Length == 0) // si la carpeta está vacía la copia también.
                {
                    mid.Add(Dir + @"/");
                }
            }
            foreach (string dirs in Directory.GetDirectories(Dir)) // do this recursively
            {
                // configurar las carpetas excluidas.
                string testDir = dirs.Substring(dirs.LastIndexOf(@"\") + 1).ToUpper();
                //if (FormBackup.excludeDirs.Contains(testDir))
                //    continue;
                foreach (object obj in GenerateFileList(dirs))
                {
                    mid.Add(obj);
                }
            }
            return mid; // devuelve la lista de archivos
        }

        private void checkMostrarConstraseña_CheckedChanged(object sender, EventArgs e)
        {
            if (checkMostrarConstraseña.Checked)
                txtContraseña.UseSystemPasswordChar = false;
            else
                txtContraseña.UseSystemPasswordChar = true;
        }

        private void botonCancelarBackup_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}  

Have a look around for some solutions involving running operations on background threads. You may need to execute your ZIP operations on another thread (if the operations are lengthy or occur all in one method call), and update the UI by calling back onto the UI thread whenever you deem some progress to have occurred inside the ZIP operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM