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

C#asp.net MvcText Files

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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"));

Solution 2 - C#

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"));
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#mathieuView Answer on Stackoverflow
Solution 2 - C#Hossein Narimani RadView Answer on Stackoverflow