Dear Reeder Dear Reeder - 1 year ago 74
ASP.NET (C#) Question

Can't get Web API to open a file using

My company is creating a new website using IIS and Visual Studio 2015. It is composed of 3 solutions. The frontend(website), the backend(webapi), and the BL(businesslogic).

The BL is a .dll we create to pass data back and forth between our backend and our Databases as well as perform a couple other functions. The BL can also be built as a console application (I typically use that to run tests as I code).

One of my functions in the BL needs to open up an HTML file (This is the only function that needs to do this. No other functions in this solution need to open a file...yet)

var sr = File.OpenText("myFile.html")

//do stuff with sr

which lives inside the bin


This works fine when I run BL as a console application. However when I build it as a .dll and reference that .dll in my backend solution it cannot find that file unless I put it in one specific folder.

C:\Program Files (x86)\IIS Express

I have spent approximately 3 hours now trying to get it to open that file from somewhere in my solution or a different folder, but no matter what I do it will only look in the IIS Express folder which seems like a an unintuitive place to put it but I'm pretty close to saying screw it and moving on to more important things than where one stupid HTML is living. I think there is probably a very easy answer to this and I would be very grateful if someone could point it out.

Answer Source

The file path you have specified only contains the file name not a full path. The path specified in File.OpenText is relative to the current working directory as described in this MSDN article

When you debug the dll is copied into the bin folder so that becomes the working folder. When you deploy it live its in IIS Express folder so that is the working folder.

If you want the file to live else where enter an absolute path or a directory relative to the current working directory.

string path = @"c:\temp\myFile.html";
var sr = File.OpenText(path);


string path = @"~/relativefolder/somewhere/myFile.html";
var sr = File.OpenText(path);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download