我在指定位置創建目錄,然後嘗試使用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