Opening File in C# Access Denied [duplicate]

2019-03-06 07:46发布

问题:

This question already has an answer here:

  • Read file from subfolder of application installation folder 4 answers

I am trying to read the content of a text file but I get the 'Access to the path is denied' exception of type 'System.UnauthorizedAccessException'. I've tried the following:

  • Ran Vs in Administrator mode
  • Checked if the file is read only
  • Checked if the file is hidden
  • Checked if the file has full control on all users

My code:

 private async void MyButton_Click(object sender, RoutedEventArgs e)
    {
        string path = @"fullpath\TextFile.txt";
        await Task.Run(() =>
       {
           string text = File.ReadAllText(path);
       });
    }

回答1:

You can't access all your files just like that in Windows Store apps. Please take a look at this MSDN page for list of locations, which your app is permited to use. Also to use most of them you will have to declare suitable Capabilities. If your file is outside this list and/or you haven't declared capabilities, you will get UnauthorizedException.

Generaly store apps shouldn't access files without user knowing about it - this is by design. If you want to access file in future, you can for example pick a file with FileOpenPicker and then access it by FutureAccessList or MostRecentlyUsed.