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.
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.
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 .
Right-click the . aspx page, and then click View Code. The code-behind file opens in the editor.
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"))
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