简体   繁体   English

从另一个项目访问Web.config

[英]Accessing Web.config from another Project

I am writing a test platform for some semi-automated testing using a Console application, but I need to get the connection string from the project I am testing. 我正在使用Console应用程序为一些半自动化测试编写测试平台,但我需要从我正在测试的项目中获取连接字符串。 I don't want to reference the other application directly or otherwise have an accessor in the project I'm testing. 我不想直接引用其他应用程序,或者在我正在测试的项目中有一个访问器。

What I've managed to do so far is create a link to the other project's Web.config file in my TestUtility project, and I've set it to Copy if newer . 到目前为止我设法做的是在我的TestUtility项目中创建一个指向另一个项目的Web.config文件的链接,并且我将它设置为Copy if newer for Copy if newer It's the only Web.config in my test project's root folder, but WebConfigurationManager.OpenWebConfiguration(null) seems to be opening some OTHER Web.config, as the only connection string in it refers to .\\SQLEXPRESS (not in any file in my solution, my path would be .\\sql2008 in this configuration - which varies). 它是我的测试项目的根文件夹中唯一的Web.config,但是WebConfigurationManager.OpenWebConfiguration(null)似乎打开了一些OTHER Web.config,因为它中唯一的连接字符串是指。\\ SQLEXPRESS(不在我解决方案的任何文件中) ,我的路径是。\\ sql2008在这个配置 - 这是不同的)。

Any hints or tips as to how to access that config section from another project? 有关如何从另一个项目访问该配置部分的任何提示或提示?

(Yay first question) (耶的第一个问题)

Better late than never: 迟到总比不到好:

var filePath = @"D:\PathToConfig\Web.config";
var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
var configFile = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

I can't take the credit for this one though, I found it here ! 我不能为这一点赢得赞誉,我在这里找到了它!

The solution I found was to open it as an XDocument and parse it manually: 我找到的解决方案是将其作为XDocument打开并手动解析:

        XDocument xdoc = XDocument.Load("Test/Web.config");

        var path = xdoc.Element("configuration").Element("connectionStrings").Element("add").Attribute("connectionString").Value;

Though if you had multiple connection strings, you would want to use the .Elements("add") method on the connectionStrings element and iterate over the various strings. 虽然如果你有多个连接字符串,你可能希望在connectionStrings元素上使用.Elements("add")方法并迭代各种字符串。

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

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