c# - 获取 Web 项目引用的类库项目中的相对文件路径

标签 c# asp.net

我有一个引用类库的 ASP.Net 网站。在类库中,我需要将文件读入内存。

在我的类库的顶层有一个名为 EmailTemplateHtml 的文件夹,其中包含我要读入的文件 MailTemplate.html

我该怎么做?

最佳答案

在 Visual Studio 中,您可以配置您的库,以便将文件复制到依赖它的任何项目的构建目录中。然后您可以在运行时获取构建目录的路径,以便读取您的文件。

分步说明,从一个新的解决方案开始:

  1. 创建您的应用程序项目和类库项目。
  2. 通过Properties->Add->Reference 从应用程序项目添加一个reference到类库项目Solution Explorer 中应用程序的上下文菜单:

    Screenshot showing the *Reference* option Screenshot showing *Reference Explorer*

  3. 在您需要读取的类库项目中创建文件,然后将其复制到输出目录 属性设置为始终复制通过 Solution Explorer 中的Properties Pane 复制:

    Screenshot showing the *Copy to Output Directory* option

  4. 类库项目 您的应用程序中(两者都将使用完全相同的代码),引用您的文件相对于 Path .GetDirectoryName(Assembly.GetExecutingAssembly().Location)。例如:

    using System.Reflection;
    using System.IO;
    
    namespace MyLibrary
    {
        public class MyClass
        {
            public static string ReadFoo()
            {
                var buildDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var filePath = buildDir + @"\foo.txt";
                return File.ReadAllText(filePath);
            }
        }
    }
    

    (请注意,在 .NET Core 之前,您可以使用相对于 System.IO.Directory.GetCurrentDirectory() 的文件路径,但这在 .NET Core 应用程序中不起作用因为 the initial working directory for .NET Core apps is the source directory instead of the build directory ,显然是因为 ASP.NET Core 需要它。)

  5. 继续从您的应用程序代码中调用您的库代码,一切都会正常进行。例如:

    using Microsoft.AspNetCore.Mvc;
    using MyLibrary;
    
    namespace AspCoreAppWithLib.Controllers
    {
        public class HelloWorldController : Controller
        {
            [HttpGet("/read-file")]
            public string ReadFileFromLibrary()
            {
                return MyClass.ReadFoo();
            }
        }
    }
    

关于c# - 获取 Web 项目引用的类库项目中的相对文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25419694/

相关文章:

css - 如何将 INSPINIA Bootstrap 添加到 Ember 应用程序

c# - 如何取消选中 C# 中子窗体的父窗体的复选框?

c# - 实现跨线程调用检查

ASP.NET配置向导使用远程sql服务器登录

c# - 如何使用引用的类在 WCF 中指定 DataContract

c# - 用户在 asp.net MVC 3 url 中输入正斜杠 "/"

c# - Active Directory LDAP - 锁定用户帐户

c# - ASP.NET MVC 3 根据一年中的时间/可访问的日期范围限制对 View 的访问

c# - 将 SSIS 包保存到本地机器

asp.net - 使用 ASP.NET 表单例份验证进行用户模拟