使用shell解压缩zip文件的参数错误

时间:2012-02-20 14:33:28

标签: c# com compression zip windows-shell

我需要解压缩位于基目录中的文件,例如sample.zip。我已经做了一个示例应用程序。我有1个输入参数 - 目标目录。以下是代码示例:

private void BInstall_Click(object sender, EventArgs e)
{
    string currentdir = Directory.GetCurrentDirectory();//Gets current directory
    string zip = currentdir + "\\" + "sample.zip";//Path to zip file
    string outPath = TBoutputPath.Text;
    exctract(zip ,outPath );
}

这是应该提取zip文件的函数:

void exctract(string name, string path)
{
    string[] args = new string[2];
    if (name.IndexOf(" ") != -1)
    {
        //we got a space in the path so wrap it in double qoutes
        args[0] += "\"" + name + "\"";
    }
    else
    {
        args[0] += name;
    }

    if (path.IndexOf(" ") != -1)
    {
        //we got a space in the path so wrap it in double qoutes
        args[1] += " " + "\"" + path + "\"";
    }
    else
    {
        args[1] +=path;
    }

    Shell32.Shell sc = new Shell32.Shell(); 
    Shell32.Folder SrcFlder = sc.NameSpace(args[0]);
    Shell32.Folder DestFlder = sc.NameSpace(args[1]);
    Shell32.FolderItems items = SrcFlder.Items();
    DestFlder.CopyHere(items , 20); 
}

DestFlder.CopyHere(items , 20);我得到NullReferenceException,我不知道为什么,因为对象不应该为null。 DestFlder是null;似乎SrcFolder已初始化但DestFlder不是。我能找到的唯一区别是DestFlder后面没有文件扩展名,但由于它是一个文件夹,所以它不应该有一个。

任何人都可以向我解释我做错了什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这个问题的答案相当......微不足道,但作为所有最简单的问题,几乎无法想到。

该文件夹不存在,因此无法引用。这段代码修正了:

        if (!Directory.Exists(args[1]))
            Directory.CreateDirectory(args[1]);

你的DJ KRAZE确实指出了脚本的另一个问题,最终可能会出现运行时错误。谢谢你!