23

How can I read the contents of a text file in my Web Application, using a relative path/URL?

The files are located in a directory at the root of my application.

I don't want to specify the full path to the file I want to access, since my test environment is not an exact mirror of my production environment.

cllpse
  • 20,858
  • 36
  • 128
  • 169

2 Answers2

46

Use Server.MapPath("/path/to/file") and pass the result of that to File.ReadAllText():

String template = File.ReadAllText(Server.MapPath("~/Templates/") + filename);
cllpse
  • 20,858
  • 36
  • 128
  • 169
Klaus Byskov Pedersen
  • 111,411
  • 28
  • 180
  • 220
7

You can use this code snippet as well.

using System.IO;
using System.Web.Hosting;

using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("~/foo.txt")))
{
    string content = sr.ReadToEnd();
}
Mehdi Golchin
  • 7,733
  • 2
  • 29
  • 36