类库中文件的路径

17

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

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

在这个项目中,文件夹Templates里面有一个名为NotificatioEmail.cshtml的文件。

我有两个应用程序:控制台应用程序和ASP.NET MVC应用程序。这个文件在控制台应用程序中能正常使用,但在MVC中出现了错误文件未找到。如何编写通用代码?
我尝试过这样:

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

但是BaseDirectory不包括bin文件夹。

1个回答

42

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

因此,您可以在两个平台上使用此代码。

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

1
这适用于asp.net,但在控制台应用程序中不起作用。 它等于null。 - user348173
1
@user348173,你能做到 System.AppDomain.CurrentDomain.RelativeSearchPath ?? System.AppDomain.CurrentDomain.BaseDirectory 吗? - p.s.w.g
那是一个非常有用的解决方案,可以将Web和控制台应用程序结合起来。 - Johnny_D
1
请确保将文件属性“复制到输出目录”设置为“始终复制”或“从不复制”,根据您的要求。 - Darshani Jayasekara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接