Reputation: 1485
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.
Upvotes: 5
Views: 16564
Reputation: 11
You can use a label message or textbox in the aspx page and you can display the file in that by using the below code, I had used a label message wit lblDisplay ID
.
lblDisplay.Text = File.ReadAllText(Server.MapPath("Give the path here"));
Upvotes: 1
Reputation: 9799
In ASP.NET the folder is really IIS's folder which is typically in C:\Windows\System32\Inetsrv\ etc.
What you will need to do is use either
Server.MapPath("TheFileName").
Or get the PhysicalApplicationPath from the Request using
Request.PhysicalApplicationPath
or
HttpRuntime.AppDomainAppPath
and go from the Request and then go from there
Upvotes: 1
Reputation: 17603
It should be something like
File.OpenRead(Server.MapPath("foo.txt"));
Upvotes: 8
Reputation: 45068
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"))
Upvotes: 2