我在指定位置创建目录,然后尝试使用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
你期望代码写入什么? – SLaks