繁体   English   中英

类库中的System.NullReferenceException

[英]System.NullReferenceException in a class library

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

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

我在网络上看过许多解决方案,但没有直接适用的方法,

  • 我正在将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 objectObject reference not set to an instance of an object

配置文件的名称必须与ExcelDNA创建的.XLL文件的名称匹配。

例如

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

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

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

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

更新

我刚刚发现这个MSDN页面描述您的具体问题,并解释了如何使用app.config文件与Office加载项: https://msdn.microsoft.com/en-us/library/16e74h9c.aspx

特别:

在[app.config文件名]框中,键入与程序集相同的名称以及扩展名.config。 例如,一个名为ExcelWorkbook1.dll的Excel项目程序集的配置文件将命名为ExcelWorkbook1.dll.config

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM