覆盖 .NET 类库的配置文件位置?
我有一个类库,我想从 .NET 应用程序调用该类库,并通过 COM 公开并从例如 excel 调用。
该类库需要从配置文件中获取一些值。当从我的 .NET 应用程序引用时,我当然可以将其所需的内容放入 app.config 中。但从 Excel 调用时我无法执行此操作。
从 Excel 调用时有没有办法覆盖配置文件的位置?
I have a class library which I want to call from my .NET application as well as expose via COM and call from for example excel.
This class library needs to get some values from a config file. When referencing from my .NET application I can of course just put the stuff it needs in the app.config. But I can't do this when calling from excel.
Is there a way to override the location for the config file when calling from excel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不完全是。您可以做的是使用 ConfigurationManager.OpenExeConfiguration 打开特定的配置文件,并从那里读取配置设置。
然而,这是一个很好的例子,说明了为什么类库直接引用应用程序配置不是一个好主意:库被设计为跨应用程序重用,并且不同的应用程序可能有不同的指定配置选项的方式。这不仅仅适用于 Excel。
相反,您应该设计您的库,以便控制其行为所需的任何选项都可以设置为属性或作为方法参数传入,以更适合该选项和 API 风格的方式为准。
Not exactly. What you can do is open a specific configuration file using ConfigurationManager.OpenExeConfiguration, and read configuration settings from there.
However, this is a good example of why it is not a good idea for class libraries to reference application configuration directly: libraries are designed to be reused across applications, and different applications may have different ways of specifying configuration options. This applies to more than just Excel.
Instead, you should design your library so that any options necessary to control it's behavior can be set as properties or passes in as method arguments, whichever is more appropriate to the option and the style of the API.
如果您正在使用应用程序设置并想要控制它们的保存/加载位置,此答案包含有关如何执行此操作的信息。
If you are using application settings and want to control where they are saved/loaded from, this answer has information on how to do this.