类库中的System.NullReferenceException

我试图在app.config中configuration一些连接string,但不断收到此错误消息,

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

我已经看过networking上的众多解决scheme,但没有直接适用,

  • 我将app.config文件复制到目标目录
  • 我引用了System.Configuration并使用ConfigurationManager
  • XML /源代码几乎是Microsoft 指南的逐字拷贝

唯一的区别是该项目是一个类库,我通过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错误Object reference not set to an instance of an object

configuration文件的名称需要与由ExcelDNA创build的.XLL文件的名称相匹配。

例如

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

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

  • 库没有自己的app.config文件,它们属于父可执行文件。
  • Excel.exe没有自己的app.config文件。
  • 连接stringConnectionCSV不存在于任何configuration文件中(如果有的话)正在运行时使用。 您可以通过检查ConfigurationManager.ConnectionStrings["ConnectionCSV"] != null优先validation,并警告用户如果密钥不存在。

在你的情况下,可能会更好地将连接string存储在用户的registry中。 白衣:

更新

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

特别:

在[app.config文件名]框中,键入与程序集相同的名称加上扩展名.config。 例如,名为ExcelWorkbook1.dll的Excel项目程序集的configuration文件将被命名为ExcelWorkbook1.dll.config