1

Form inside an ApiController. I need to read content of a file embedded inside the project. But I can't resolve the correct path

[HttpPost]
public HttpResponseMessage DoSomething()
{
    String content = System.IO.File.ReadAllText(@"~\SomeFolder\file.txt");
}

Doing like this the resolved path point to:

C:...\bin\Debug\~\SomeFolder\file.txt

instead of

C:...\SomeFolder\file.txt

Does anyone have any idea how to solve this under OWIN Self Host?

VP.
  • 15,509
  • 17
  • 91
  • 161
Gavello
  • 1,399
  • 2
  • 13
  • 25

1 Answers1

0

In general, it does not make sense to try to access a file inside a project. All the files necessary for deployment (dlls, assets, txts,...) should be copied to a separated folder so that when we need to deploy, we just need to copy that folder.

You should set the file as Copy To Output and try:

String content = System.IO.File.ReadAllText(@"SomeFolder\file.txt");

which is resolved to

C:...\bin\Debug\SomeFolder\file.txt

To make the code work with OWIN, you could take a look at this answer How do you resolve a virtual path to a file under an OWIN host?. It suggests using HostingEnvironment.MapPath and falling back to manipulating file paths manually in self host scenario.

Community
  • 1
  • 1
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • I'm trying to send an html formatted email so I need to grab the html template somehow and substitute the required parts. I would have used Server.MapPath("~/SendMail.htm") but under Owin self host I have not this option any other options you are aware of? – Gavello Aug 11 '15 at 01:25
  • @Gavello: Owin does not run inside IIS, so `Server.MapPath` should not be possible. If you host owin inside IIS, maybe you can try: http://stackoverflow.com/questions/16557122/microsoft-web-api-how-do-you-do-a-server-mappath . If you make your files relative to your root in both console host and IIS host, the solution in this answer should also work. – Khanh TO Aug 11 '15 at 02:12