繁体   English   中英

如何在C#中将ProgressBar添加到SharpZipLib实用程序

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

我需要在项目中包含一个进度条,但是我不确定该怎么做或如何成功调用要更新的方法。 我要包含的代码如下,非常感谢:

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();
        }
    }
}  

看看一些涉及在后台线程上运行操作的解决方案。 您可能需要在另一个线程上执行ZIP操作(如果这些操作很长或全部在一个方法调用中发生),并且只要您认为ZIP操作内部已取得一些进展,就可以通过回调UI线程来更新UI。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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