2014-02-05 133 views
0

我想壓縮一個文件與DotNetZip庫。我正在從文件讀取路徑並將zip保存到該文件。但程序崩潰並拋出。這是我的代碼:訪問拒絕.tmp路徑

using (ZipFile zip = new ZipFile()) 
{ 
    zip.AddDirectory(dir + "\\OUTPUT_FOLDERS"); 

    StreamReader sr = new StreamReader(dir + "\\Tools\\SettingsForPath"); 
    string path = sr.ReadToEnd(); 
    sr.Close(); 

    zip.Save(path + "\\SavedZip.zip"); 
    Directory.Delete(dir + "\\OUTPUT_FOLDERS", true); 
} 

,這裏是我的錯誤:

System.UnauthorizedAccessException: Access to the path 'C:\Users\DotNetZip-nvan5kb5.tmp' is denied. 
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) 
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) 
at System.IO.FileStream..ctor(String path, FileMode mode) 
at Ionic.Zip.SharedUtilities.CreateAndOpenUniqueTempFile(String dir, Stream& fs, String& filename) 
at Ionic.Zip.ZipFile.get_WriteStream() 
at Ionic.Zip.ZipFile.Save() 
at Ionic.Zip.ZipFile.Save(String fileName) 

回答

0

我認爲問題出在哪個目錄保存臨時文件創建您沒有權限。嘗試設置臨時文件夾一樣

zip.TempFileFolder = @"D:\tempfolder"; 

和保存時,使用

zip.Save(@"D:\tempfolder\my.zip"); 
+0

該文件夾可能不存在temp文件夾。事實上,這種驅動可能不存在。看到我的答案。 –

+0

是的。也許這就是爲什麼我說試着用'ZipFile'對象的'TempFileFolder'屬性設置已知的文件夾。 – Sameer

2

您正在試圖寫入C:\Users目錄,你無權這樣做。

使用Path.GetTempPath()獲取您可以編寫的目錄的名稱。

查看http://msdn.microsoft.com/en-us/library/system.io.path.gettemppath.aspx瞭解更多信息。

如下你會使用它:

using (ZipFile zip = new ZipFile()) 
{ 
    zip.TempFileFolder = System.IO.Path.GetTempPath(); 

    // etc. 
+0

我不完全確定如何以及在哪裏應該使用這個..你能寫一個例子嗎? – orglce

+0

@orglce查看更新的答案。 –

+1

它引發錯誤。它說訪問路徑被拒絕。 – orglce

0

如果用戶要真有寫訪問嘗試檢查,如果你通過代碼有寫特權時在光盤上寫入前使用.. System.Security.Principal.WindowsIdentity .GetCurrent()。名稱爲您的名字.. 如果真的只是暫時用作說明上述

string path = @"c:\temp"; 
string NtAccountName = @"MyDomain\MyUserOrGroup"; 

DirectoryInfo di = new DirectoryInfo(path); 
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All); 
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount)); 

foreach (AuthorizationRule rule in rules) 
{ 
//If we find one that matches the identity we are looking for 
if (rule.IdentityReference.Value.Equals(NtAccountName,StringComparison.CurrentCultureIgnoreCase)) 
    { 
    //Cast to a FileSystemAccessRule to check for access rights 
    if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData)>0) 
    { 
     Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path)); 
    } 
    else 
    { 
     Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path)); 
    } 
} 
}