Jason Z. Jason Z. - 3 months ago 25
ASP.NET (C#) Question

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

Answer

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"));