访问文件夹被拒绝 C#

Access to folder Denied C#

我是一个相当新的 C# 程序员,我 运行 遇到了一个超出我修复能力的错误。

目前我正在编写一个 discord 机器人,在尝试实例化和 Program 对象时,它 returns 一个 "Access is denied error"。 问题是错误指的是文件夹,而不是文件,我已经尝试了很多方法来修复它。

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

此时我基本上没有想法了。异常讯息的完整详情如下:

System.UnauthorizedAccessException HResult=0x80070005 Message=Access to the path 'C:\Users\XXX\source\repos\discordBot\discordBot\bin\Debug' is denied. Source=mscorlib StackTrace: 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, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access) at train_bot.Program.d__3.MoveNext() in C:\Users\XXX\source\repos\discordBot\discordBot\Program.cs:line 46 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at train_bot.Program.Main(String[] args) in C:\Users\XXX\source\repos\discordBot\discordBot\Program.cs:line 21

不太详细的版本

System.UnauthorizedAccessException: 'Access to the path 'C:\Users\SettingAdmin\source\repos\discordBot\discordBot\bin\Debug' is denied.'

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
        }
    }
}

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

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")

如错误所述,您无权访问该文件夹。如果您 运行 在调试模式下使用它,请确保您 运行 visual studio 是管理员,这样您就可以在开发环境中忽略所有这些。如果已部署,请确保您的程序的帐户 运行 对该文件夹具有适当的权限。