path to file in class library

user348173 picture user348173 · Mar 14, 2013 · Viewed 18k times · Source

I have a class libary project (NotificationTemplate) which return content of file:

public static class Template
{
    public static string NotificatioEmail
    {
        get { return File.ReadAllText("Templates\\NotificatioEmail.cshtml"); }
    }
}

In this project is located folder Templates with NotificatioEmail.cshtml file.

Also, I have two application: console app and ASP.NET MVC app. The file returned fine in the console app, but in the MVC I get error file not found. How to write universally?
I tryed this:

Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Templates",
             "NotificatioEmail.cshtml")

but BaseDirectory don't include bin folder.

Answer

p.s.w.g picture p.s.w.g · Mar 14, 2013

As you said BaseDirectory works for console apps. For MVC applications, use RelativeSearchPath instead.

So you can use this code for both platforms

var appDomain = System.AppDomain.CurrentDomain;
var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
Path.Combine(basePath, "Templates", "NotificatioEmail.cshtml");