2

I'm trying to read a text file with File.ReadAllText and FileStream, but for some reason I get the System.UnauthorizedAccessException every time.

 class consultas
{
    public consultas()
    {


    }

    private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";

    public string getInativos()
    {
        try
        {
            // string path = Directory.GetCurrentDirectory();
            this.Inativos = File.ReadAllText(this.Inativos);

        }
        catch(Exception e)
        {
            throw e;


        }
        return this.Inativos;


    }
}

Why? I have permissions in that folder, so why do I get this exception?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150

2 Answers2

5

Based on your code, you are either trying to read a Folder since you didn't specify a extension on your File Path here:

private string Inativos = @"C:\Users\Mathias Cruz\Desktop\helloWorld\helloWorld\Consultas";

It will definitely throw a UnauthorizedAccessException error. So make sure you have the exact file path together with its extension.

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
1

Because the path is a directory. Please check your file address. This method needs a file address. Here is a sample code:

File.ReadAllText("C:\\yourfile.txt");
Morteza Asadi
  • 414
  • 3
  • 13