我有一个引用类库的 ASP.Net 网站。在类库中,我需要将文件读入内存。
在我的类库的顶层有一个名为 EmailTemplateHtml
的文件夹,其中包含我要读入的文件 MailTemplate.html
。
我该怎么做?
最佳答案
在 Visual Studio 中,您可以配置您的库,以便将文件复制到依赖它的任何项目的构建目录中。然后您可以在运行时获取构建目录的路径,以便读取您的文件。
分步说明,从一个新的解决方案开始:
- 创建您的应用程序项目和类库项目。
通过Properties->Add->Reference 从应用程序项目添加一个reference到类库项目 从 Solution Explorer 中应用程序的上下文菜单:
在您需要读取的类库项目中创建文件,然后将其复制到输出目录 属性设置为始终复制 或通过 Solution Explorer 中的Properties Pane 复制:
在 类库项目 或 您的应用程序中(两者都将使用完全相同的代码),引用您的文件相对于
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 需要它。)继续从您的应用程序代码中调用您的库代码,一切都会正常进行。例如:
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/