2015-05-08 72 views
0

我不確定爲什麼在文件夾內容成功壓縮後發生此異常。這是對的嗎?使用ZipFile壓縮:在mscorlib.dll中發生類型爲「System.IO.IOException」的未處理異常

錯誤:類型System.IO.IOException'的未處理的異常出現在mscorlib.dll 附加信息:過程不能訪問該文件「C:\ TEMP \ pack.zip」,因爲它正在使用通過另一個進程。

private static string directoryPath = @"c:\Temp\"; 
    static void Main(string[] args) 
    { 
     zipFolder(directoryPath, [email protected]"pack.zip"); 
    } 

    public static void zipFolder(string targetPath, string resultPath) 
    { 
     ZipFile.CreateFromDirectory(targetPath, resultPath,CompressionLevel.Optimal,true); 
    } 
+1

您試圖壓縮的文件之一正在被另一個進程訪問。 –

+0

無關,但你應該看看['Path.Combine'](https://msdn.microsoft.com/en-us/library/system.io.path.combine%28v=vs.110%29。 aspx),而不是通過字符串連接組裝一個有效的路徑。 – Alex

回答

1

你在做你的代碼正在讀取C的含量是什麼:\ TEMP試圖創建在同一目錄中的zip文件。

相反,應用程序目錄中創建一個文件,稍後將文件複製到Temp文件夾。

 var newFilePath = Path.Combine(directoryPath, "pack.zip"); 
     if(File.Exists(newFilePath))File.Delete(newFilePath); //Remove file if it exists 
     if (File.Exists("pack.zip")) File.Delete("pack.zip"); //Remove file if it exists 
     zipFolder(directoryPath, "pack.zip"); 
     File.Move("pack.zip", newFilePath); 
相關問題