Jason Z.
Jason Z.

Reputation: 53

Getting the application directory for File I/O in C#

I am trying to pass in a file path to a StreamReader without writing the full path because I will be uploading this to a web server. For some reason I can't seem to get this to work. Here's the code snippet that giving me some problems:

StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"\files\randomlist.txt");

This works when I run it locally in Visual Studio, but it doesn't work when I upload it to my website. The full path of the file I am trying to read is:

C:\Users\Jason\Documents\Visual Studio 2013\WebSites\WordFriends\files\randomlist.txt

So my question is, how can I write the path such that it works on my web server? Or if you have an alternative solution, please let me know. Also, could someone also explain why just doing this doesn't work?

StreamReader reader = new StreamReader(@"files\randomlist.txt");

Thanks,
Jason

Upvotes: 0

Views: 602

Answers (2)

George Polevoy
George Polevoy

Reputation: 7671

Using Server.MapPath("~") would give the root directory of your website.

It's not recommended to concatenate pants with +, use Path.Combine(a, b) instead.

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66439

Try using this instead. The call to Server.MapPath returns the physical path corresponding the virtual path you provide, assuming "files\randomlist.txt" is the correct virtual path.

StreamReader reader =
    new StreamReader(HttpContext.Current.Server.MapPath(@"files\randomlist.txt"));

Upvotes: 3

Related Questions