Question Background:
I have a WebApi controller who's logic code relies on reading data contained in a number of XML files. These XML files have been included in the App_Data
folder of the WebApi project.
The Issue:
I'm trying to use the relative path of the XML files in the following way:
[System.Web.Http.HttpGet]
public string CallerOne()
{
string docOne = @"~\AppData\DocOne.xml";
string poll = @"~\AppData\Poll.xml";
var response = _Caller.CallService(docOne, poll);
return ConvertXmlToJson(response);
}
When running the WebApi code and calling the Url to the CallerOne
method I receive the following error:
An exception of type 'System.IO.DirectoryNotFoundException'
occurred in System.Xml.dll but was not handled in user code
Additional information: Could not find a part of the path
'C:\Program Files (x86)\IIS Express\~\AppData\FPS.xml'.
I also want to eventually publish this to Azure and include these files.
How can I use the relative path to read in the XML files in the App_Data
folder?
Ended up finding the answer.
The following is needed to read the relative paths in a WebApi project:
var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/yourXmlFile.xml");
As jdweng inferred several months back, Environment.GetEnvironmentVariable("AppData") would seem to be the preferred method. The OP's auto-accepted answer and that give quite different results. For example, using both of those in my project, I get:
C:\\Projects\\PlatypusReports\\PlatypusReports\\App_Data\\yourXmlFile.xml
...for the OP's long-winded code, namely this:
var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/yourXmlFile.xml");
...and this:
C:\\Users\\cshannon\\AppData\\Roaming
...for jdweng's code, to wit:
string appData = Environment.GetEnvironmentVariable("AppData");
OTOH, this code:
string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
returns:
C:\\Projects\\PlatypusReports\\PlatypusReports\App_Data\
So it's very similar in results (if not methodology) to the first example above. I actually got it from a question I asked almost two years ago, which I had forgotten about.
I'm not positive if jdweng's approach would work as expected once the app is deployed on a server, but I have much more confidence in it than the other approaches.
Can anyone verify?
The accepted answer here has 237 upvotes at time of typing, so seems pretty reliable, albeit 6 years old (42 in dog years, which may be a good sign).
Your approach is fine. You just had some tpying error, You wrote
string docOne = @"~\AppData\DocOne.xml";
But it should have been
string docOne = @"~\App_Data\DocOne.xml";
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