拒绝访问.tmp路径

时间:2014-02-05 16:56:38

标签: c# asp.net .net winforms visual-studio-2010

我正在尝试使用DotNetZip库压缩文件。我正在从文件中读取路径并将zip保存到该文件。但程序崩溃和抛出。这是我的代码:

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)

3 个答案:

答案 0 :(得分:4)

您正在尝试写入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.

答案 1 :(得分:0)

我认为问题是您创建的临时文件在哪个目录中没有权限。尝试设置临时文件夹,如

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

以及保存时使用

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

答案 2 :(得分: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));
    }
 }
}