1

我改编了这篇文章中的代码来制作一个压缩和复制目录的程序。我在我的代码中包含了一个后台工作程序,因此我可以异步运行压缩例程以防止界面冻结。这是我改编的代码:

private void StartZipping()
{
    var zipWorker = new BackgroundWorker { WorkerReportsProgress = true };

    zipWorker.DoWork += ZipWorkerWork;
    zipWorker.RunWorkerCompleted += ZipWorkerCompleted;

    zipWorker.RunWorkerAsync();
}

private void ZipWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    WriteLogEntry("Zip Worker Finished");
    var sleep = new Timer();
    sleep.Tick += SleepTick;
    sleep.Interval = DEBUG ? SecondsToMilliseconds(45) : MinutesToMilliseconds(15);
    sleep.Start();
}

private void ZipWorkerWork(object sender, DoWorkEventArgs e)
{
    WriteLogEntry("Zip Worker Started");
    var checkedItems = GetCheckedItems();
    if (checkedItems.Count() <= 0) return;

    foreach (var p in checkedItems)
        ZipFiles(((BackupProgram)p.Tag));
}

private static void ZipFiles(BackupProgram program)
{
    var zipPath = string.Format("{0}{1}.ZIP", TempZipDirectory, program.Name.ToUpper());
    WriteLogEntry(string.Format("Zipping files from '{0}' to '{1}'...", program.Path, zipPath));
    try
    {
        var emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        if (File.Exists(zipPath)) File.Delete(zipPath);

        var fs = File.Create(zipPath);
        fs.Write(emptyzip, 0, emptyzip.Length);
        fs.Flush();
        fs.Close();
        //fs = null;

        //Copy a folder and its contents into the newly created zip file
        var sc = new Shell32.ShellClass();
        var srcFlder = sc.NameSpace(program.Path);
        var destFlder = sc.NameSpace(zipPath);
        var items = srcFlder.Items();
        destFlder.CopyHere(items, 20);
        //sc = null;

        System.Threading.Thread.Sleep(1000);
        ZippedPrograms.Add(zipPath);
        WriteLogEntry("Zip Succeeded");
    }
    catch (Exception ex)
    {
        WriteLogEntry(string.Format("Zipping Failed: {0} >> {1}", ex.Message, ex.InnerException.Message));
        MessageBox.Show(ex.InnerException.Message, ex.Message);
    }
}

internal class BackupProgram
{
    public string Name { get; set; }
    public string Path { get; set; }

    public BackupProgram(string name, string path)
    {
        Name = name;
        Path = path;
    }
}

显然,就目前而言,所有压缩窗口都会在命中此代码时显示。我试图模仿示例程序(隐藏窗口),但只取得了微不足道的成功。窗户被隐藏了,但拉链只完成了部分。这是修改后的代码,其行为与文章的几乎相同:

private static void ZipFiles(BackupProgram program)
{
    try
    {
        var zipPath = string.Format("{0}{1}.ZIP", TempZipDirectory, program.Name.ToUpper());

        var i = new ProcessStartInfo(AppDomain.CurrentDomain.BaseDirectory + "zip.exe");
        i.Arguments = string.Format("\"{0}\" \"{1}\"", program.Path, zipPath);
        //i.CreateNoWindow = false;
        //i.WindowStyle = ProcessWindowStyle.Normal;
        i.CreateNoWindow = true;
        i.WindowStyle = ProcessWindowStyle.Hidden;

        if (File.Exists(zipPath))
        {
            WriteLogEntry(string.Format("'{0}' exists, deleting...",zipPath));
            File.Delete(zipPath);
        }

        var process = Process.Start(i);
        WriteLogEntry(string.Format("Zipping files from '{0}' to '{1}'...", program.Path, zipPath));

        process.WaitForExit();
        ZippedPrograms.Add(zipPath);
        WriteLogEntry("Zip Succeeded");
    }
    catch (Exception ex)
    {
        WriteLogEntry(string.Format("Zipping Failed: {0} >> {1}", ex.Message, ex.InnerException.Message));
        MessageBox.Show(ex.InnerException.Message, ex.Message);
    }
}

我想知道的是:有没有办法使用我原来的改编代码,但隐藏进度窗口?

谢谢!

编辑

以下是示例解决方案的代码(可从文章顶部的链接下载),即 zip.exe:

using System;
using System.IO;

namespace zip
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class Class1
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {

            //Create an empty zip file
            byte[] emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            FileStream fs = File.Create(args[1]);
            fs.Write(emptyzip, 0, emptyzip.Length);
            fs.Flush();
            fs.Close();
            fs = null;

            //Copy a folder and its contents into the newly created zip file
            Shell32.ShellClass sc = new Shell32.ShellClass();
            Shell32.Folder SrcFlder = sc.NameSpace(args[0]);
            Shell32.Folder DestFlder = sc.NameSpace(args[1]);
            Shell32.FolderItems items = SrcFlder.Items();
            DestFlder.CopyHere(items, 20);

            //Ziping a file using the Windows Shell API creates another thread where the zipping is executed.
            //This means that it is possible that this console app would end before the zipping thread 
            //starts to execute which would cause the zip to never occur and you will end up with just
            //an empty zip file. So wait a second and give the zipping thread time to get started
            System.Threading.Thread.Sleep(1000);

        }
    }
}
4

2 回答 2

1

这个链接提供了一个很好的例子来完成同样的事情: http: //geraldgibson.net/dnn/Home/CZipFileCompression/tabid/148/Default.aspx

您必须向下滚动链接页面才能看到答案。希望这可以帮助!

于 2012-11-03T23:52:53.653 回答
1

如果您想在没有窗口、进度或其他 UI 显示的情况下进行压缩,并且想在后台运行它,隐藏...那么为什么不使用 dotnetzip 之类的 zip 库,只需分离一个调用必要逻辑的线程来执行您的zip 操作工作流程。

http://dotnetzip.codeplex.com http://dotnetzip.codeplex.com/wikipage?title=CS-Examples

于 2012-11-03T20:16:40.373 回答