System.NullReferenceException 在 class 图书馆

System.NullReferenceException in a class library

我正在尝试在 app.config 中配置一些连接字符串,但不断收到此错误消息,

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

我在网上看了很多解决方案,但没有一个直接适用,

唯一的区别是该项目是一个 class 库,我通过 ExcelDNA 将其公开给 Excel。

我需要做些什么才能让它与 Excel 一起工作吗?

这是 XML、

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

这是源代码(已获得 using System.Configuration 以及必要的参考),

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

以上行抛出 Object reference not set to an instance of an object 错误。

  • 库没有自己的 app.config 文件,它们属于父可执行文件。
  • Excel.exe 没有自己的 app.config 文件。
  • 连接字符串 ConnectionCSV 不存在于运行时使用的任何配置文件中(如果有的话)。您可以通过先检查是否 ConfigurationManager.ConnectionStrings["ConnectionCSV"] != null 并在密钥不存在时警告用户来验证这一点。

在您的情况下,最好将连接字符串存储在用户的注册表中。惠特:

更新:

我刚刚在 MSDN 上找到了这个页面,它描述了您的确切问题并解释了您如何可以app.config 文件与 Office 加载项一起使用:https://msdn.microsoft.com/en-us/library/16e74h9c.aspx

具体来说:

In the [app.config filename] box, type the same name as the assembly plus the extension .config. For example, a configuration file for an Excel project assembly called ExcelWorkbook1.dll would be named ExcelWorkbook1.dll.config.

配置文件的名称需要与 ExcelDNA 创建的 .XLL 文件的名称相匹配。

例如

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

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