我有一个类库项目(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
文件夹。
答案 0 :(得分:40)
正如您所说BaseDirectory
适用于控制台应用。对于MVC应用程序,请改用RelativeSearchPath
。
因此,您可以将此代码用于两个平台
var appDomain = System.AppDomain.CurrentDomain;
var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
Path.Combine(basePath, "Templates", "NotificatioEmail.cshtml");