magicode118
magicode118

Reputation: 1474

Get path of file located in NuGet package's directory from same package in C#

I have a .NET Framework (4.7) solution which is referencing a NuGet package. This NuGet package should read from an html and an xml file. These files are both located within the packages' folder (NuGet package) and they are NOT needed by the solution directly, but only by the NuGet package itself.

How can I refer to these files when running the solution that is consuming the mentioned NuGet package?

I tried with ./ but all this does is point to the root directory of my solution instead.

The actual call that I am trying is: File.ReadAllText(path).

I also tried to set Copy to Output Directory property of the files to Copy always and use Build Action as Content. This is copying these files in the packages/<package name>/Content/*.html for example and somehow I guess I can get this path, such as the solution given here: Getting the path of a nuget package programmatically

But this looks complicated to me for such a seemingly simple task. What is the clean way of doing this?

Edit: Renamed question to specify that setting a resource is not an option in this case as some of the functions I'm consuming in the NuGet package are requesting a file path and not a resource.

Upvotes: 1

Views: 2570

Answers (1)

SilentTremor
SilentTremor

Reputation: 4902

If this is a nuget package created by you, under any circumstances at runtime a external file should't be used! someone can alter it, if is needed add it as embedded resource.

Anyway, at runtime I would get the folder where the .dll stays like this:

 var currentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
 var rootFolder = Assembly.GetExecutingAssembly().Location.Split(currentAssemblyName)[0];

Edit - should work for both .NET Framework or dotnet core

My mistake, to get the real path for the DLL you need to search for the Assembly, because ExecutingAssembly is from where the .exe was launched

 var assembly = AppDomain.CurrentDomain
                          .GetAssemblies()
                          .SingleOrDefault(assembly => assembly.GetName().Name == "my.awsome.nuget");
 var location = assembly.Location; 

Upvotes: 2

Related Questions