2012-02-20 141 views
1

我需要解壓縮位於基本目錄中的文件,例如sample.zip。我爲此做了一個示例應用程序。我有1個輸入參數 - 目標目錄。以下是代碼示例:參數錯誤使用shell解壓縮zip文件

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,我不知道爲什麼,因爲對象不應該爲空。它是空的DestFlder;似乎SrcFolder已初始化,但DestFlder不是。唯一的區別是我可以找到的是,DestFlder後面沒有文件擴展名,但由於它是一個文件夾,它不應該有一個文件擴展名。

任何人都可以解釋我做錯了什麼,以及如何解決?

+0

你可以使用你的調試器來確定哪個對象(DestFlder,items)爲空,如果有的話?同時讓shell爲你做這件事是一個有趣的問題,使用一個解壓縮庫可能是最簡單的,例如, SharpZipLib – Rup 2012-02-20 14:35:50

+0

DestFlder顯示爲空,並給我「沒有關於此對象的更多信息可以被發現」的錯誤報告。那麼20是一個int,所以這個應該是一個問題:D – TheBW 2012-02-20 14:39:53

+1

看看你的代碼,你在哪裏有+ =「\」+「\\」在字符串zip = currentdir +「\\」+「樣本中定義。 zip「; //壓縮文件的路徑也許你正在附加一個額外的」\「調試,並確保你正在尋找什麼位於以下字符串currentdir = Directory.GetCurrentDirectory(); //獲取當前目錄 string zip = currentdir +「\\」+「sample.zip」; //壓縮文件的路徑也許你有一些路徑問題.. – MethodMan 2012-02-20 14:43:15

回答

1

這個問題的答案是相當......微不足道的,但作爲所有最簡單的問題,幾乎不可能想到。

該文件夾不存在,因此無法引用。此代碼一塊固定的:

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

禰DJ KRAZE確實點到另一個問題,可能有它可能得到一個運行時錯誤最終腳本。謝謝你!