簡體   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