Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to read in a text file from the server in asp.net-mvc

People also ask

What is MVC 5 controller with read write actions?

It is used to handle the user request coming from the browser. It will check the request from the browser and identify the action method and return the respective view. A controller is inherited from “ControllerBase” class which is inside the “System. Web.


If the file should not be directly available via URL, you should put it in App_Data.

For reading it, just use:

var fileContents = System.IO.File.ReadAllText(Server.MapPath(@"~/App_Data/file.txt"));

Ok this way it works for me (VS2017)

  1. Set the Build Action of the file.txt to Content
  2. Check if Copy to output directory is not set to 'Do not copy'
  3. Use HostingEnvironment.MapPath(@"~/App_Data/file.txt") (thanks to Hong comment)

    var fileContents = 
        System.IO.File.ReadAllText(HostingEnvironment.MapPath(@"~/App_Data/file.txt"));