【发布时间】:2012-02-17 00:01:38
【问题描述】:
我正在指定位置创建一个目录,然后我尝试使用 StreamWriter 访问它,但它一直说“访问被拒绝。”
有人知道会发生什么吗?
我的代码是这样的:
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, String maybeFullPath) 在 System.IO.FileStream.Init(字符串路径、FileMode 模式、FileAccess 访问、Int32 权限、Boolean useRights、FileShare 共享、Int32 bufferSize、FileOptions 选项、SECURITY_ATTRIBUTES secAttrs、String msgPath、Boolean bFromProxy、Boolean useLongPath) 在 System.IO.FileStream..ctor(字符串路径、FileMode 模式、FileAccess 访问、FileShare 共享、Int32 bufferSize、FileOptions 选项) 在 System.IO.StreamWriter.CreateFile(字符串路径,布尔附加) 在 System.IO.StreamWriter..ctor(字符串路径,布尔附加,编码编码,Int32 缓冲区大小) 在 System.IO.StreamWriter..ctor(字符串路径) 在 C:\Temp\AlertDemoSolution\AlertDemoSolution\AlertDemoSolution\MySqlUnitTest.cs:line 23 中的 AlertDemoSolution.MySqlUnitTest.TestMethod1() 处
【问题讨论】:
-
您希望该代码写入什么内容?