Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a file located in a same folder where my page resides in in ASP.NET?

Tags:

c#

asp.net

How do I read a file located in a same folder where my page resides in in ASP.NET (C#)? I have a page called mypage.aspx and I'm trying to read in a file called foo.txt residing in a same directory as this page.

Is there a way to open that file for reading with File.OpenRead()? Providing a relative path like File.OpenRead("foo.txt") fails b/c of the location of the file.

like image 623
Alex Khvatov Avatar asked Feb 11 '11 20:02

Alex Khvatov


People also ask

How do I reference a file in the same folder?

To reference a file in a subdirectory, write the directory name in front of the path, plus a forward slash, e.g. subdirectory/my-image. jpg.

How do I access Wwwroot files?

in the wwwroot folder as shown below. You can access static files with base URL and file name. For example, we can access above app. css file in the css folder by http://localhost:<port>/css/app.css .

How do you open code behind?

Right-click the . aspx page, and then click View Code. The code-behind file opens in the editor.


2 Answers

It should be something like

File.OpenRead(Server.MapPath("foo.txt"));
like image 130
Matten Avatar answered Oct 10 '22 04:10

Matten


You should try File.OpenRead(Server.MapPath("foo.txt")).

If MapPath doesn't expand/can't find the proper path at this point then try it while specifying the relative path to the page in question starting from the sites virtual root (using the tilde (~) at the beginning of the string to indicate this), i.e. File.OpenRead(Server.MapPath("~/path/foo.txt"))

like image 28
Grant Thomas Avatar answered Oct 10 '22 05:10

Grant Thomas