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.
A Relative Path binds policies to a specific relative path location (for example /test/path ). When the API Gateway receives a request on the specified Relative Path, it invokes the specified policy or policy chain.
A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.
Relative File Path: It describes the path of the file relative to the location of the current web page file. Example 1: It shows the path of the file present in the same folder of the current web page file. html.
Use Server.MapPath("/path/to/file")
and pass the result of that to File.ReadAllText()
:
String template = File.ReadAllText(Server.MapPath("~/Templates/") + filename);
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With