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

后端 未结 2 610
花落未央
花落未央 2020-12-29 17:39

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 q

相关标签:
2条回答
  • 2020-12-29 18:14

    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"));
    
    0 讨论(0)
  • 2020-12-29 18:35

    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"));
      
    0 讨论(0)
提交回复
热议问题