leora leora - 2 months ago 13
C# Question

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

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?


Answer

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