如何从web.config文件中检索connectionString?

时间:2021-10-13 20:19:00

I am writing an client application in C# which will be supposed to change ConnectionString settings in a web.config file from another application I wrote. How can I achieve this goal?

我正在用C#编写一个客户端应用程序,它应该从我编写的另一个应用程序中更改web.config文件中的ConnectionString设置。我怎样才能实现这个目标?

Is there a way to load the web.config file in my application and read/change its data object orientated? Or do I need to parse it as if beeing a complete 'unknown' XML file?

有没有办法在我的应用程序中加载web.config文件并读取/更改其面向数据对象?或者我是否需要解析它就好像是一个完整的“未知”XML文件?

2 个解决方案

#1


If you're doing this from another application, you can use the VirtualDirectoryMapping class:

如果您是从其他应用程序执行此操作,则可以使用VirtualDirectoryMapping类:

VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(@"C:\Inetpub\wwwroot\YourApplication", true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);


// Get the connectionString
Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
string connection = config.ConnectionStrings.ConnectionStrings["YourConnectionString"];

#2


I would use RMI to query the other application for the ConnectionString.

我会使用RMI查询ConnectionString的其他应用程序。

#1


If you're doing this from another application, you can use the VirtualDirectoryMapping class:

如果您是从其他应用程序执行此操作,则可以使用VirtualDirectoryMapping类:

VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(@"C:\Inetpub\wwwroot\YourApplication", true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);


// Get the connectionString
Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
string connection = config.ConnectionStrings.ConnectionStrings["YourConnectionString"];

#2


I would use RMI to query the other application for the ConnectionString.

我会使用RMI查询ConnectionString的其他应用程序。