类库中的文件路径

时间:2013-03-14 05:33:26

标签: c# asp.net-mvc class-library

我有一个类库项目(NotificationTemplate),它返回文件内容:

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

在此项目中找到文件夹TemplatesNotificatioEmail.cshtml文件。

另外,我有两个应用程序:控制台应用程序和ASP.NET MVC应用程序。该文件在控制台应用程序中返回正常,但在MVC中我收到错误file not found。怎么写普遍?
我试过这个:

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

BaseDirectory不包含bin文件夹。

1 个答案:

答案 0 :(得分:40)

正如您所说BaseDirectory适用于控制台应用。对于MVC应用程序,请改用RelativeSearchPath

因此,您可以将此代码用于两个平台

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