In one of my controller actions I need to read in a text file that has a bunch of refere开发者_运维技巧nce data in it. Right now I simply put it in the "/Content" directory.
My questions are:
- Is this the "right" place to put this file or should I put it in another directory?
- What is the best way to read in a text file in asp.net-mvc that is sitting on the server?
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)
- Set the Build Action of the file.txt to Content
- Check if Copy to output directory is not set to 'Do not copy'
Use
HostingEnvironment.MapPath(@"~/App_Data/file.txt")
(thanks to Hong comment)var fileContents = System.IO.File.ReadAllText(HostingEnvironment.MapPath(@"~/App_Data/file.txt"));
精彩评论