访问我刚刚创建的目录时出现UnauthorizedAccessException

时间:2012-01-23 16:28:43

标签: c# .net

我正在指定位置创建一个目录,然后我尝试使用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;
    }

完整的堆栈跟踪:

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)    在System.IO.FileStream..ctor(字符串路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项)    在System.IO.StreamWriter.CreateFile(String path,Boolean append)    在System.IO.StreamWriter..ctor(String path,Boolean append,Encoding encoding,Int32 bufferSize)    在System.IO.StreamWriter..ctor(String path)    在C:\ Temp \ AlertDemoSolution \ AlertDemoSolution \ AlertDemoSolution \ MySqlUnitTest.cs中的AlertDemoSolution.MySqlUnitTest.TestMethod1():第23行

2 个答案:

答案 0 :(得分:5)

StreamWriter写入文件 你不能写一个目录。

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

答案 1 :(得分:2)

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