2012-01-23 76 views
2

我在指定位置创建目录,然后尝试使用StreamWriter访问它,但它一直说“访问被拒绝”。访问我刚刚创建的目录时出现UnauthorizedAccessException

有没有人有任何想法会发生什么?

我的代码是这样的:

if (!Directory.Exists(dirPath)) 
     Directory.CreateDirectory(dirPath); 
    var a = HasWritePermissionOnDir(dirPath); <- This is only here to see if the value is true and it is. 
    tw = new StreamWriter(dirPath); 

    public static bool HasWritePermissionOnDir(string path) 
    { 
     var writeAllow = false; 
     var writeDeny = false; 
     var accessControlList = Directory.GetAccessControl(path); 
     if (accessControlList == null) 
      return false; 
     var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); 
     if (accessRules == null) 
      return false; 

     foreach (FileSystemAccessRule rule in accessRules) 
     { 
      if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) continue; 

      if (rule.AccessControlType == AccessControlType.Allow) 
       writeAllow = true; 
      else if (rule.AccessControlType == AccessControlType.Deny) 
       writeDeny = true; 
     } 

     return writeAllow && !writeDeny; 
    } 

完整堆栈跟踪:

在System.IO .__ Error.WinIOError(的Int32的errorCode,字符串maybeFullPath) 在System.IO.FileStream.Init(字符串路径,FileMode模式,FileAccess访问,Int32权限,布尔useRights,FileShare共享,Int32 bufferSize,FileOptions选项,SECURITY_ATTRIBUTES secAttrs,字符串msgPath,布尔bFromProxy,布尔useLongPath) at System.IO.FileStream..ctor(String path,FileMode mode ,FileAccess访问,FileShare共享,Int32 bufferSize,FileOp (String path,Boolean append,Encoding encoding,Int32 bufferSize) at System.IO.StreamWriter。 .ctor在C(字符串路径) 在AlertDemoSolution.MySqlUnitTest.TestMethod1():\ TEMP \ AlertDemoSolution \ AlertDemoSolution \ AlertDemoSolution \ MySqlUnitTest.cs:行23

+0

你期望代码写入什么? – SLaks

回答

5

StreamWriter写入到一个文件中。
您无法写入目录。

您可能想要在目录中创建一个文件。

+0

DERP !!!非常感谢!你刚才提醒我今天要适当地睡一会儿! :) – user1045602

2

您无法将StreamWriter指向目录。您需要将它指向FileStream中的目录中的文件。