0

I have a class library that has some text files with Build Action = Content. These text files are read by a function within the class library. To get the location of the text files I use this:

var filePath = System.IO.Path.Combine(
    AppDomain.CurrentDomain.BaseDirectory,
    "AFolder",
    "textFileName.txt");

var fileContent = System.IO.File.ReadAllText(filePath);

I have successfully retrieved the content of the text file when I called the function from a unit test. The text file is in C:\MySolution\MyProject.Test\bin\Debug\AFolder\textFileName.txt.

I have another web app that references this class library. When I called the function to read the text file from the web app, it couldn't find the text file because it tried to get the file from C:\MySolution\MyProject.Web\AFolder\textFileName.txt while the text file is actually in C:\MySolution\MyProject.Web\bin\AFolder\textFileName.txt.

So my problem is calling AppDomain.CurrentDomain.BaseDirectory doesn't always work. What should I use instead to get the folder location?

Endy Tjahjono
  • 24,120
  • 23
  • 83
  • 123

2 Answers2

1

Found the answer from the link on the right by using System.Reflection.Assembly.GetExecutingAssembly().CodeBase:

var libPath = System.IO.Path.GetDirectoryName(
    new Uri(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase
    ).LocalPath
);

var filePath = System.IO.Path.Combine(
    libPath,
    "AFolder",
    "textFileName.txt");

var fileContent = System.IO.File.ReadAllText(filePath);
Community
  • 1
  • 1
Endy Tjahjono
  • 24,120
  • 23
  • 83
  • 123
0

You can try System.WebHttpRuntime.BinDirectory to get the physical path to the /bin directory for the current application.

EDIT 1:

Another way to get without using System.Web is using AppDomain.CurrentDomain.SetupInformation.PrivateBinPath, this property provides list of directories under the application base directory that are probed for private assemblies.

Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
  • I need to add reference to System.Web to my class library? I'd rather not do that if I can. The class library needs to be able to run outside of the web app. – Endy Tjahjono Jan 31 '16 at 16:30