17

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

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

在这个项目中,位于Templates带有NotificatioEmail.cshtml文件的文件夹中。

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

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

BaseDirectory不包括bin文件夹。

4

1 回答 1

42

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

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

var appDomain = System.AppDomain.CurrentDomain;
var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
Path.Combine(basePath, "Templates", "NotificatioEmail.cshtml");
于 2013-03-14T05:36:35.553 回答