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
8775 silver badges20 bronze badges
asked Jul 5, 2011 at 12:48
3
  • 1
    "right" depends on a lot of things; size, nature, how often it is updated, etc Commented Jul 5, 2011 at 12:51
  • use this library easy to implemet in asp.net filehelpers.com Commented Jul 5, 2011 at 12:53
  • 17
    really. use a library to read a text file?! Commented Jul 5, 2011 at 12:54

2 Answers 2

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
32.7k19 gold badges92 silver badges121 bronze badges
answered Jul 5, 2011 at 12:55
5
  • if the file should be available for public put it in the Content or Upload (if uploaded) folders Commented Jul 5, 2011 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. Commented May 12, 2014 at 2:44
  • Doesn't work for me because this results includes the routing of the url. Commented Dec 24, 2015 at 8:51
  • Doesn't work for me when I publish the project to server, but in debug mode using HostingEnvironment.MapPath works Commented Sep 21, 2016 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. Commented Feb 13, 2017 at 3: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"));
    
answered Sep 21, 2016 at 16:04
1
  • 2
    This seems to be the answer for 2017+ Commented Feb 23, 2017 at 6:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.