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:
- 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?
asked Jul 5, 2011 at 12:48
-
1"right" depends on a lot of things; size, nature, how often it is updated, etcMarc Gravell– Marc Gravell2011年07月05日 12:51:03 +00:00Commented Jul 5, 2011 at 12:51
-
use this library easy to implemet in asp.net filehelpers.comrahularyansharma– rahularyansharma2011年07月05日 12:53:07 +00:00Commented Jul 5, 2011 at 12:53
-
17really. use a library to read a text file?!user156888– user1568882011年07月05日 12:54:34 +00:00Commented Jul 5, 2011 at 12:54
2 Answers 2
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
-
if the file should be available for public put it in the Content or Upload (if uploaded) foldersmare– mare2011年07月05日 14:39:55 +00:00Commented Jul 5, 2011 at 14:39
-
21Thank you for the tip. HostingEnvironment.MapPath(@"~/App_Data/file.txt") works too if Server is not easy to come by.Hong– Hong2014年05月12日 02:44:17 +00:00Commented May 12, 2014 at 2:44
-
Doesn't work for me because this results includes the routing of the url.Mike de Klerk– Mike de Klerk2015年12月24日 08:51:29 +00:00Commented 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 worksHossein Narimani Rad– Hossein Narimani Rad2016年09月21日 15:59:15 +00:00Commented 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.DtechNet– DtechNet2017年02月13日 03:12:15 +00:00Commented Feb 13, 2017 at 3:12
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"));
answered Sep 21, 2016 at 16:04
-
2This seems to be the answer for 2017+user585968– user5859682017年02月23日 06:20:33 +00:00Commented Feb 23, 2017 at 6:20
lang-cs