Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read contents of a file using a relative path in a Web Application

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.

like image 729
cllpse Avatar asked Dec 02 '09 12:12

cllpse


People also ask

What is relative path in API?

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.

What is relative path?

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.

What is an HTML relative path?

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.


2 Answers

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

String template = File.ReadAllText(Server.MapPath("~/Templates/") + filename);
like image 179
Klaus Byskov Pedersen Avatar answered Oct 23 '22 13:10

Klaus Byskov Pedersen


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();
}
like image 31
Mehdi Golchin Avatar answered Oct 23 '22 13:10

Mehdi Golchin