Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read a text file within a class library in dotnet

I have a class library using dotnet 6 which encapsulates the logic for an integration.

This project needs a text file which is basically a template that I’ll merge values into during runtime. The file has Build Action = None and Copy to output directory = Copy always. It is in the root of the class library project.

The class library is consumed by a web api, also in dotnet 6.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to read this file, from within the class library but when debugging, it raises a FileNotFoundException because it is looking for it in the source folder, but not in the output directory.

If I put the file in the root of the project, it is properly found.

This is the line I’m using to read the file:

var template = File.ReadAllText("file-name.txt");

>Solution :

You will have to use Assembly.GetExecutingAssembly().Location to get location/path.

using System.IO;    
using System.Reflection;
    public static string ExecutionDirectoryPathName()
        {
             var dirPath = Assembly.GetExecutingAssembly().Location;
             dirPath = Path.GetDirectoryName(dirPath);
             return Path.GetFullPath(Path.Combine(dirPath, "\YourFolder\file.txt"));
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading