Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a file's last modified date in ASP.NET Core MVC?

I'm porting a small MVC 5 website to MVC 6 to spot breaking changes. Stuff is breaking.

The MVC 5 code uses @File.GetLastWriteTime(this.Server.MapPath(this.VirtualPath)) to get the timestamp, as recommended here. Apparently in MVC 6, the .cshtml page no longer has Server or VirtualPath members. What's the new incantation?

like image 389
Paul Williams Avatar asked Oct 30 '22 06:10

Paul Williams


1 Answers

Revisiting my own question 18 months later... the framework is now ASP.NET Core 2.0 MVC and it seems the framework, documentation and best practices have changed a bit.

You should use a FileProvider as described in the MS docs. There's no point in recreating that article here, but be sure to:

  • Add an IHostingEnvironment to the Startup constructor parameters, and save it off in a local variable, as described in the docs
  • In Startup.ConfigureServices(), call services.AddSingleton(HostingEnvironment.ContentRootFileProvider); to register an IFileProvider service, also described in the docs
  • Add an IFileProvider to the controller's constructor parameters, and save it off in a local variable

Then to actually get the last modified date, the controller will look something like this:

public class HomeController : Controller
{
    private IFileProvider _fileProvider;

    public HomeController(IFileProvider fileProvider)
    {
        _fileProvider = fileProvider;
    }

    public IActionResult Index()
    {
        DateTimeOffset lastModifiedDate = _fileProvider.GetFileInfo(@"Views\Home\Index.cshtml").LastModified;
        // use it wisely...
        return View();
    }
like image 132
Paul Williams Avatar answered Nov 15 '22 04:11

Paul Williams