2014-02-05 100 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)); 
    } 
} 
}