0

I want to include an XML file in the bin directory of my web application/web service. I've included the bin folder in my project in Visual Studio and added the file. I set its Build Action to "Content" and Copy to Output Directory to "Copy Always". When my code goes to find it, I use

string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!dir.EndsWith(@"\")) dir += @"\";

to get the directory and return it as appPath, where appPath is (unescaped version):

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\vs\0c7655f\d4908928\assembly\dl3\5cf9fd67\fdc52284_ffa7d201\

then I append the file name of my XML file (where string filename = "myXmlFile.xml") to read it:

StreamReader reader = new StreamReader(appPath + filename);

But I get an exception on that line of code, that it could not find my file. I am handling for escaping of the slashes fine, so it is not that. When I checked the physical directory that the path points to, it was not copied to that directory, and that is the cause of the exception. So how do I get my file to get copied there?

vapcguy
  • 7,097
  • 1
  • 56
  • 52

1 Answers1

1

How about using HostingEnvironment.ApplicationPhysicalPath

var dir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin\\filename.xml")

See related question how to get the application path in asp.net?.

Community
  • 1
  • 1
klashar
  • 2,519
  • 2
  • 28
  • 38
  • Actually - we later found that I shouldn't have been using `bin` for where my file should live, if we wanted to do any writes to it. Any time you write from a web app or service to content files in folders under it, it resets the site - so any static global variables become cleared. Just a note of caution for anyone that wants to follow my footsteps. When we moved it to the same level as the site, everything was fine - so we just don't use `bin` in that path, anymore. Cheers! – vapcguy Apr 12 '17 at 21:25