57

In one of my controller actions I need to read in a text file that has a bunch of reference data in it. Right now I simply put it in the "/Content" directory.

My questions are:

  1. Is this the "right" place to put this file or should I put it in another directory?
  2. What is the best way to read in a text file in asp.net-mvc that is sitting on the server?
cr0ss
  • 877
  • 5
  • 20
leora
  • 188,729
  • 360
  • 878
  • 1,366

2 Answers2

112

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"));
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
mathieu
  • 30,974
  • 4
  • 64
  • 90
  • if the file should be available for public put it in the Content or Upload (if uploaded) folders – mare Jul 05 '11 at 14:39
  • 21
    Thank you for the tip. HostingEnvironment.MapPath(@"~/App_Data/file.txt") works too if Server is not easy to come by. – Hong May 12 '14 at 02:44
  • Doesn't work for me because this results includes the routing of the url. – Mike de Klerk Dec 24 '15 at 08:51
  • Doesn't work for me when I publish the project to server, but in debug mode using HostingEnvironment.MapPath works – Hossein Narimani Rad Sep 21 '16 at 15:59
  • Is there any architectural concerns for just creating a ViewBag.Property in the cshtml file itself or should this file content be served from the Controller? I have several files with static text for certain pages (poor man CMS) and I don't think it'd be a good fit for a database because the data will rarely EVER change. – DtechNet Feb 13 '17 at 03:12
23

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"));
    
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116