Set up .NET library project correctly, so that I don't need to copy DLL's and other files to calling programs

163 Views Asked by At

I always face the following problem at a certain moment with .Net library projects: I have to copy over resources such as dll's to programs that call the .Net library.

For example, I have a library that does some sound manipulation. I have a consumer program (call it a test project) that has a reference to the library project. In the library project, I use a c# wrapper class that calls a c++ dll. I also have a .config file with certain strings. I face the following problem:

When the test project is calling the Library, I get DllNotFound exceptions. The C# wrapper can't find the c++ dll. So I copy over the c++ dll to certain folders in the test project (root, bin, bin/debug) until the DLLNotFound exception is "fixed" (clearly, I'm not exactly sure where it needs to be stored). I also need to copy over the .config file from the library to the test project, although I set the property "Copy if newer" in visual studio.

I had similar problems with say text files that contain SQL commands that I need to run. So I have a file named "commands.sql" in my library project, which I call via something like:

//example
public static class Configurator
{
    private static string _basePath = String.Empty;

    public static string BasePath
    {
        get
        {
            if (_basePath == String.Empty)
            {
                var basePath = Environment.CurrentDirectory;
                var projectName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
                basePath = basePath.Substring(0, basePath.LastIndexOf(projectName));
                _basePath = basePath + projectName;
            }

            return _basePath;
        }
    }
}


private static string LoadSqlScript()
{
    return System.IO.File.ReadAllText($"{Configurator.BasePath}\\scripts\\commands.sql");
}

But this doesn't work when I call this from the test project. I still need to copy over the script to the calling program manually.

What is the correct way to deal with this? I must be missing something, right? I expect not to have to result to post build scripts to "automate" this, right?

1

There are 1 best solutions below

0
On
  1. You might the following link interesting: https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order. It contains information about how DLL are searched for when you include them with P/Invoke in your library.

  2. Correctly, if the libraries are not installed in one of the well known locations listed in 1, then you would probably need to include the DLLs with your build. For that, you would set them to "Copy to output directory, if newer" via the .NET project configuration (which then triggers the correct MSBuild targets).