【问题标题】:UnauthorizedAccessException when accessing a directory I just created访问我刚刚创建的目录时出现 UnauthorizedAccessException
【发布时间】: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() 处

【问题讨论】:

  • 您希望该代码写入什么内容?

标签: c# .net


【解决方案1】:

StreamWriter 写入文件。
您不能写入目录。

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

【讨论】:

  • DERP!!!非常感谢大佬!!你刚刚提醒我今天要好好睡一觉! :)
【解决方案2】:

您不能将 StreamWriter 指向目录。您需要将其指向该目录中文件的 FileStream。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多