Home > Mobile >  Read a text file within a class library in dotnet
Read a text file within a class library in dotnet

Time:10-18

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.

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");

CodePudding user response:

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"));
        }
  • Related