c# – 获取Web项目引用的类库项目中的相对文件路径
我有一个引用类库的ASP.Net网站.在类库中,我需要将文件读入内存.
在我的类库的顶层有一个名为EmailTemplateHtml的文件夹,其中包含我想要阅读的文件MailTemplate.html. 我怎样才能做到这一点? 解决方法
在Visual Studio中,您可以配置库,以便将文件复制到依赖于它的任何项目的构建目录中.然后,您可以在运行时获取构建目录的路径,以便读取您的文件.
从新的解决方案开始,逐步说明: >创建应用程序项目和类库项目.
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(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |