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 开发者_如何学JAVAb/c of the location of the file.
It should be something like
File.OpenRead(Server.MapPath("foo.txt"));
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"))
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
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"));
精彩评论