Thursday, March 31, 2011

How can i retrieve a connectionString from a web.config file?

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?

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?

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

    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"];
    
    Marcus : Works perfectly, thanks!
    CMS : You're welcome Marcus
  • I would use RMI to query the other application for the ConnectionString.

    dotnetdev : I think you mean WMI :)
    Scott Muc : No, I meant RMI (Remote Method Invocation). I guess it's called .Net Remoting these days and now is lumped in with the whole WCF stack.

0 comments:

Post a Comment