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

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

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

我怎样才能做到这一点?

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

从新的解决方案开始,逐步说明:

  1. 创建应用程序项目和类库项目。
  2. 通过解决方案资源管理器中应用程序的上下文菜单中的Properties – > Add – > Reference,从应用程序项目添加类库项目的引用

    显示* Reference *选项的屏幕截图 屏幕截图显示* Reference Explorer *

  3. 在类库项目中创建需要读取的文件,然后通过“ 解决方案资源管理器”中的“ 属性”窗格将其“ 复制到输出目录”属性设置为“始终 复制”“如果更新则复制”

    显示*复制到输出目录*选项的屏幕截图

  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应用程序中不起作用,因为.NET Core应用程序的初始工作目录是源目录而不是构建目录 ,显然是因为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(); } } } 
 public static string ExecutionDirectoryPathName { var dirPath = Assembly.GetExecutingAssembly().Location; dirPath = Path.GetDirectoryName(dirPath); return Path.GetFullPath(Path.Combine(dirPath, "\EmailTemplateHtml\MailTemplate.html")); } 

如果要查找assembly所在的路径; 从程序集中,然后使用以下代码:

  public static string ExecutionDirectoryPathName { get { var dirPath = Assembly.GetExecutingAssembly().Location; dirPath = Path.GetDirectoryName(dirPath); return dirPath + @"\"; } } 

我不确定您对类库中的文件夹的含义,但如果您希望按如下方式构建路径,则可以使用当前工作目录:

 System.IO.Directory.GetCurrentDirectory() 

然后,您可以使用Path.Combine()方法来构建文件路径。