Access to folder Denied C#

0

I'm a fairly new C# Programmer, and I've run into an error beyond my ability to fix.

Currently I'm working on coding a discord bot, and upon trying to instantiate and Program object, it returns an "Access is denied error". 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
  • Ensuring my account has permissions to access the files and folder
  • Changing the location of the project files
  • Restarting 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();

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

The less detailed version

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
        }
    }
}
c#
access-denied
asked on Stack Overflow Nov 25, 2018 by Angus Longmore

2 Answers

3

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

You probably intended something like

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

answered on Stack Overflow Nov 25, 2018 by Klaus Gütter • edited Oct 24, 2019 by Sibeesh Venu
0

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. If its deployed, make sure the the account running your program has appropriate rights to the folder.

answered on Stack Overflow Nov 25, 2018 by calingasan

User contributions licensed under CC BY-SA 3.0