【问题标题】:path to file in class library类库中文件的路径
【发布时间】:2013-03-02 08:50:25
【问题描述】:

我有一个返回文件内容的类库项目(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 文件夹。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 这适用于 asp.net,但不适用于控制台应用程序。等于 null。
    • @user348173 你能做到System.AppDomain.CurrentDomain.RelativeSearchPath ?? System.AppDomain.CurrentDomain.BaseDirectory 吗?
    • 这是一个非常有用的解决方案,可以结合 Web 和控制台应用程序。
    • 确保根据您的要求将文件属性“复制到输出目录”设置为“始终复制”或“如果从不复制”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    相关资源
    最近更新 更多