Chiramisu
Chiramisu

Reputation: 4726

IO.StreamReader(filename) Sillyness

Why is it that I can't use a relative path for IO.StreamReader("Resources/file.txt")?

I'm working with a web app, so obviously the file isn't going to be in the same absolute location between my development machine and the server.

How can I fix my filename path so it finds the file?

For reference, I have a file (relative to the page calling it) at path "Resources/file.txt" but the stupid function is looking in root "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE." And just in case it matters, I'm on .NET 3.5 at the moment.

Thanks. :)

Upvotes: 1

Views: 1891

Answers (2)

Khalid Rahaman
Khalid Rahaman

Reputation: 2302

Use HttpContext.Current.Server.MapPath(filename) to find the relative path to your file as a string then pass this to IO.StreamReader like so:

Dim sr As New IO.StreamReader(HttpContext.Current.Server.MapPath(filename))
Dim text As String = DirectCast(sr, IO.TextReader).ReadToEnd() 'gives you text

Upvotes: 2

Guffa
Guffa

Reputation: 700382

That's because your working folder is not where the web root is, it's where the application is. When developing it's where the Visual Studio application is, on a live server it will be where the IIS application is.

Use a virtual path, and the Server.MapPath method to map it to a folder relative to the web root:

StreamReader(Server.MapPath("Resources/file.txt"))

Upvotes: 2

Related Questions