【问题标题】:Access to folder Denied C#访问文件夹被拒绝 C#
【发布时间】:2018-11-25 16:33:56
【问题描述】:

我是一个相当新的 C# 程序员,我遇到了一个我无法修复的错误。

目前我正在编写一个不和谐的机器人,并在尝试实例化和Program 对象时,它返回一个“访问被拒绝错误”。 问题是错误指的是文件夹,而不是文件,我已经尝试了很多东西来修复它。

  • 以管理员身份运行 Visual Studio
  • 确保我的帐户有权访问文件和文件夹
  • 更改项目文件的位置
  • 重新启动 Visual Studio
  • 从零开始重新编码项目
  • 确保文件夹和文件不是“只读”

在这一行抛出错误:=> new Program().MainAsync().GetAwaiter().GetResult();

在这一点上,我基本上没有想法。异常消息的完整详细信息如下:

System.UnauthorizedAccessException H结果=0x80070005 消息=拒绝访问路径“C:\Users\XXX\source\repos\discordBot\discordBot\bin\Debug”。 源=mscorlib 堆栈跟踪: 在 System.IO.__Error.WinIOError(Int32 错误代码,字符串可能全路径) 在 System.IO.FileStream.Init(字符串路径、FileMode 模式、FileAccess 访问、Int32 权限、Boolean useRights、FileShare 共享、Int32 bufferSize、FileOptions 选项、SECURITY_ATTRIBUTES secAttrs、String msgPath、Boolean bFromProxy、Boolean useLongPath、Boolean checkHost) 在 System.IO.FileStream..ctor(字符串路径,FileMode 模式,FileAccess 访问) 在 C:\Users\XXX\source\repos\discordBot\discordBot\Program.cs:line 46 中的 train_bot.Program.d__3.MoveNext() 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter.GetResult() 在 C:\Users\XXX\source\repos\discordBot\discordBot\Program.cs:line 21 中的 train_bot.Program.Main(String[] args)

不太详细的版本

System.UnauthorizedAccessException: '对路径'C:\Users\SettingAdmin\source\repos\discordBot\discordBot\bin\Debug'的访问被拒绝。'

using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Discord;
using Discord.Commands;
using Discord.WebSocket;

namespace train_bot
{
    class Program
    {

        private DiscordSocketClient Client;
        private CommandService Commands;
        static void Main(string[] args)
        => new Program().MainAsync().GetAwaiter().GetResult();


        private async Task MainAsync()
        {
            //configuring client 
            Client = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel = LogSeverity.Debug    //changes detail in log
            });

            Commands = new CommandService(new CommandServiceConfig
            {
                CaseSensitiveCommands = true,
                DefaultRunMode = RunMode.Async,
                LogLevel = LogSeverity.Debug
            });

            Client.MessageReceived += Client_MessageReceived;
            await Commands.AddModulesAsync(Assembly.GetEntryAssembly());

            Client.Ready += Client_Ready;
            Client.Log += Client_Log;

            string Token = "";
            using (var Steam = new FileStream(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace(@"bin\Debug\netcoreapp2.0", @"Token.txt"), FileMode.Open, FileAccess.Read))using (var ReadToken = new StreamReader(Steam))
            {
                Token = ReadToken.ReadToEnd();
            }

            await Client.LoginAsync(TokenType.Bot, Token);
            await Client.StartAsync();

            await Task.Delay(-1);
        }

        private async Task Client_Log(LogMessage Message)
        {
            Console.WriteLine($"{DateTime.Now} at {Message.Source}] {Message.Message}");

        }

        private async Task Client_Ready()
        {
            await Client.SetGameAsync("Hentai King 2018", "", StreamType.NotStreaming);
        }

        private async Task Client_MessageReceived(SocketMessage arg)
        {
            //Configure the commands
        }
    }
}

【问题讨论】:

    标签: c# access-denied


    【解决方案1】:

    问题可能是您尝试将目录作为文件打开。你构造的路径是:

    Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace(@"bin\Debug\netcoreapp2.0", @"Token.txt")

    这只有在 Assembly.GetEntryAssembly().Location 确实包含字符串 @"bin\Debug\netcoreapp2.0" 时才有效。

    你可能想要类似的东西

    Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), @"Token.txt")

    【讨论】:

    • 同意。您可以使用任何目录重现访问被拒绝错误:using (var stream = new FileStream( Directory.GetCurrentDirectory() , FileMode.Open, FileAccess.Read)) {}。在我看来,框架确实应该给出一个更明确的错误,说“无法将目录作为文件打开”
    • @ChrisFCarroll:几十年前它被确定为“后备错误”。如果遇到 NTFS 权限,“找不到文件”将是 Windows 95 时代程序的响应。所以现在他们不能再改变它而不冒破坏代码的风险。也许至少 .NET Core 有一个更明显的例外?当然,假设他们没有将确切的例外放入 .NET 标准本身。
    • 好吧,显然 Filestream 从 1.3 开始就是 .NET Standard 的一部分。所以这种行为不会改变。但是描述很有趣:“操作系统不允许指定路径的访问权限,例如当访问权限为写入或读取并且文件或目录设置为只读访问时。”它总是采用路径,而不是文件路径。出于许多目的,文件夹被实现为磁盘上的分类文件。然后是 Zip 容器,自 Vista 以来,它们在很大程度上被视为磁盘上的文字文件夹。
    • 谢谢 :),我实现了你的建议,更改了 .txt 文件的位置,它工作了。真的很感激
    【解决方案2】:

    就像错误所说的那样,您无权访问该文件夹。如果您在调试模式下运行它,请确保您以管理员身份运行 Visual Studio,这样您就可以忽略开发环境中的所有内容。如果已部署,请确保运行您的程序的帐户对该文件夹具有适当的权限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多