Search code examples
c#excelexcel-dna

System.NullReferenceException in a class library


I'm trying to configure some connection strings in app.config, but keep getting this error message,

System.NullReferenceException: Object reference not set to an instance of an object.

I've looked at numerous solutions on the web, but nothing directly applies,

  • I'm copying the app.config file to the target directory
  • I've referenced System.Configuration and am using ConfigurationManager
  • The XML / source is almost a verbatim copy of the Microsoft guidelines

The only difference is that the project is a class library, which I'm exposing to Excel via ExcelDNA.

Is there something special I need to do to get this to work with Excel?

Here's a snippet of the XML,

<configuration>
    <connectionStrings>
        <add name="ConnectionCSV" providerName="System.Data.OleDb" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;" />
    </connectionStrings>  
</configuration>

This is the source code (have got a using System.Configuration along with necessary reference),

string constr = ConfigurationManager.ConnectionStrings["ConnectionCSV"].ConnectionString;

The above line throws the Object reference not set to an instance of an object error.


Solution

  • The name of the configuration file needs to match the name of the .XLL file that is created by ExcelDNA.

    e.g.

    MyApp-AddIn.xll -> MyApp-AddIn.xll.config

    MyApp-AddIn64.xll -> MyApp-AddIn64.xll.config