简体   繁体   English

访问文件夹拒绝的C#

[英]Access to folder Denied C#

I'm a fairly new C# Programmer, and I've run into an error beyond my ability to fix. 我是一个相当新的C#程序员,但遇到了无法修复的错误。

Currently I'm working on coding a discord bot, and upon trying to instantiate and Program object, it returns an "Access is denied error". 目前,我正在编写一个discord bot的代码,并尝试实例化和Program对象时,它返回“访问被拒绝错误”。 The issue is that the error is referring to a folder, not a file and I've tried a bunch of stuff to fix it. 问题是该错误是指一个文件夹,而不是文件,我已经尝试了很多方法对其进行修复。

  • Running Visual Studio as administrator 以管理员身份运行Visual Studio
  • Ensuring my account has permissions to access the files and folder 确保我的帐户有权访问文件和文件夹
  • Changing the location of the project files 更改项目文件的位置
  • Restarting visual Studio 重新启动Visual Studio
  • Recoding the project off a clean sheet 用干净的纸重新编码项目
  • Ensuring the folder and files are not "Read Only" 确保文件夹和文件不是“只读”

The error is thrown at this line: => new Program().MainAsync().GetAwaiter().GetResult(); 在此行抛出错误: => new Program().MainAsync().GetAwaiter().GetResult();

I'm basically out of ideas at this point. 在这一点上,我基本上没有主意。 The full details of the exception message are as follows: 异常消息的详细信息如下:

System.UnauthorizedAccessException HResult=0x80070005 Message=Access to the path 'C:\\Users\\XXX\\source\\repos\\discordBot\\discordBot\\bin\\Debug' is denied. System.UnauthorizedAccessException HResult = 0x80070005 Message =拒绝访问路径'C:\\ Users \\ XXX \\ source \\ repos \\ discordBot \\ discordBot \\ bin \\ Debug'。 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 Source = mscorlib StackTrace:位于System.IO .__ Error.WinIOError(Int32 errorCode,字符串可能是FullPath)位于System.IO.FileStream.Init(字符串路径,FileMode模式,FileAccess访问,Int32权限,布尔值useRights,FileShare共享,Int32 bufferSize, FileOptions选项,SECURITY_ATTRIBUTES secAttrs,字符串msgPath,布尔bFromProxy,布尔useLongPath,布尔checkHost在System.IO.FileStream..ctor(字符串路径,FileMode模式,FileAccess访问)在C的train_bot.Program.d__3.MoveNext()中: \\ Users \\ XXX \\ source \\ repos \\ discordBot \\ discordBot \\ Program.cs:System 46中System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)的Line 46。 C:\\ Users \\ XXX \\ source \\ repos \\ discordBot \\ discordBot \\ Program.cs:line 21中train_bot.Program.Main(String [] args)处的Runtime.CompilerServices.TaskAwaiter.GetResult()

The less detailed version 不太详细的版本

System.UnauthorizedAccessException: 'Access to the path 'C:\\Users\\SettingAdmin\\source\\repos\\discordBot\\discordBot\\bin\\Debug' is denied.' '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
        }
    }
}

The problem may be that you try to open a directory as file. 问题可能是您尝试将目录打开为文件。 The path you construct is: 您构造的路径是:

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

This would only work if Assembly.GetEntryAssembly().Location indeed contains the string @"bin\\Debug\\netcoreapp2.0". 仅当Assembly.GetEntryAssembly()。Location确实包含字符串@“ bin \\ Debug \\ netcoreapp2.0”时,此方法才有效。

You probably intended something like 你可能打算像

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

Like the error said, you don't have access to that folder. 像错误说的那样,您无权访问该文件夹。 If you are running it on debug mode make sure you run visual studio as administrator so you get to ignore all that on dev environment. 如果在调试模式下运行它,请确保以管理员身份运行Visual Studio,以便忽略开发环境上的所有内容。 If its deployed, make sure the the account running your program has appropriate rights to the folder. 如果已部署,请确保运行程序的帐户对该文件夹具有适当的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM