1

My development environment is ASP .Net Core 3.1 Razor Pages (non-MVC), in VS 2019 Community (version 16.4.5).

I am using the following code to display files in the wwwroot/documents directory:

public class IndexModel : PageModel
{
    private readonly ApplicationDbContext _context;
    private readonly IWebHostEnvironment _env;

    public IndexModel(ApplicationDbContext context, IWebHostEnvironment hostingEnvironment)
    {
        _context = context;
        _env = hostingEnvironment;
    }

    string webRootPath = _env.WebRootPath;
    string docsPath = Path.Combine(webRootPath, "documents");

    public void OnGet()
    {
        var files = Directory.GetFiles(docsPath, "*.*", SearchOption.TopDirectoryOnly); 
    }
}

I am getting error CS0236, A field initializer cannot reference the non-static field, method, or property 'IndexModel._env'.

The error shows on this line:

string webRootPath = _env.WebRootPath;

on _.env

Any help appreciated

1 Zero 3 Tech
  • 117
  • 3
  • 8
  • 2
    The error message is telling you what the problem is. You have a field - `webRootPath` - which is accessing another non-static field - `_env` - when it initializes. This is not allowed by the compiler. As in the answer to [this question](https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property), _"You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these ...."_ – stuartd Mar 01 '20 at 00:22

0 Answers0