Get the relative path of a file in a class library project referenced by a web project
In Visual Studio, you can configure your library to copy the file to the build directory of any project that depends on it. Then you can get the path to the build directory at runtime to read your file.
Step by step instructions, starting with fresh mortar:
- Create an application project and a class library project.
-
Add a reference to the class library project from the application project via Properties-> Add-> Reference from the application context menu in Solution Explorer:
-
Create a file in the class library project that you want to read, then set its Copy to Output Directory property to Always Copy or Copy if newer through the Properties pane in Solution Explorer:
-
Within a class library project or your application (or will work with exactly the same code), specify your file relative to
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
. For example: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); } } }
(Note that prior to .NET Core, you could have used the file path relative instead
System.IO.Directory.GetCurrentDirectory()
, but this does not work in a .NET Core app as the starting working directory for .NET Core apps is the source directory, not the build directory , apparently because it was necessary for ASP.NET Core.) -
Go ahead and name your library code from your application code and everything should work fine. eg:
using Microsoft.AspNetCore.Mvc; using MyLibrary; namespace AspCoreAppWithLib.Controllers { public class HelloWorldController : Controller { [HttpGet("/read-file")] public string ReadFileFromLibrary() { return MyClass.ReadFoo(); } } }
source to share
If you want to find the path where the assembly is located; from within the assembly, use the following code:
public static string ExecutionDirectoryPathName
{
get
{
var dirPath = Assembly.GetExecutingAssembly().Location;
dirPath = Path.GetDirectoryName(dirPath);
return dirPath + @"\";
}
}
source to share