Sdílet prostřednictvím


How to: Access and Modify ASP.NET Configuration Files Remotely 

The System.Configuration and System.Web.Configuration types allow your application to access the configuration files on a remote server. In particular, you can open and modify the Machine.config or a Web.config file in any Microsoft Internet Information Services (IIS) application or its child directories on a remote server. This topic:

  • Demonstrates how to set the remote server to allow a client computer to access the server configuration files.

  • Provides a console application, to run on the client computer, that can read or modify the server configuration files.

  • Discusses the security considerations to take into account.

To access configuration files on a remote server, the client computer must be able to communicate with the server. To enable this communication, a remote configuration component must be installed on the server.

The client computer then accesses the server configuration files by calling the ASP.NET configuration API through the remote configuration component. For more information, see Editing ASP.NET Remote Configuration Files.

NoteNote

If the requested configuration file does not exist, the .NET Framework, running on the server, returns a configuration file consisting entirely of inherited settings that apply to the specified path. If your application requests an update, a new file is created. When running the console application, you must enter a valid server name. This is because ASP.NET passes this name directly to the operating system. You must likewise enter a fully qualified user name with the domain name prefix.

To set up the remote server

  1. Install the remote configuration component on the server using the ASP.NET IIS Registration tool (Aspnet_regiis.exe) with the config+ command, as shown in the following code.

    Aspnet_regiis config+
    
  2. Programmatically or manually, make sure that the Web.config file of the IIS server's "Default Web Site" contains values similar to the following:

    <appSettings>
        <add key="keyName1", value = "this entry value"/>
        <add key="keyName2", value = "this entry value"/>
        <add key="keyName3", value = "this entry value"/>
    </appSettings>
    

To update the remote configuration files using a console application

  • Run the console application provided in the code example below to update the Web.config file of the Default Web Site on the remote server. This example assumes that the user running the client application has administrative privileges on the remote server. You can use either of these two commands.

    >remoteconfiguration machineName
    >remoteconfiguration machineName domainName\userName password
    

Example

Imports System
Imports System.Configuration
Imports System.Web.Configuration
Imports System.Collections.Specialized


' This example dDemonstrates how to access and modify remote 
' configuration files


Public Class RemoteConfiguration
    
    
    ' The application entry point.
    Public Shared Sub Main(ByVal args() As String) 
    
        ' This string  contains the name of 
        ' the remote server.
        Dim machineName As String = String.Empty
        
        ' Get the user's input.
        If args.Length > 0 Then
            ' Get the name of the remote server.
            ' The machine name must be in the format
            ' accepted by the operating system.
            machineName = args(0)
            
            ' Get the user name and password.
            If args.Length > 1 Then
                Dim userName As String = args(1)
                Dim password As String = String.Empty
                If args.Length > 2 Then
                    password = args(2)
                End If 
                ' Update the site configuration.
                UpdateConfiguration(machineName, userName, password)
            Else
                ' Update the site configuration.
                UpdateConfiguration(machineName)
            End If
        Else
            Console.WriteLine("Enter a valid server name.")
        End If
    
    End Sub 'Main
    
    
    ' Update the configuration file using the credentials
    ' of the user running this application. Tthen,
    ' call the routine that reads the configuration 
    ' settings.
    ' Note that the system issues an error if the user
    ' does not have administrative privileges on the server.
    Public Overloads Shared Sub _
    UpdateConfiguration(ByVal machineName As String)
        Try
            Console.WriteLine("MachineName:  [{0}]", machineName)
            Console.WriteLine("UserDomainName:  [{0}]", _
                Environment.UserDomainName)
            Console.WriteLine("UserName:  [{0}]", _
                Environment.UserName)

            ' Get the configuration.
            Dim config As Configuration = _
                WebConfigurationManager.OpenWebConfiguration("/", _
                "Default Web Site", Nothing, machineName)

            ' Add a new key/value pair to appSettings.
            Dim count As String = _
                config.AppSettings.Settings.Count.ToString()
            config.AppSettings.Settings.Add("key_" + count, _
                "value_" + count)

            ' Save changes to the file.
            config.Save()

            ' Read the new appSettings.
            ReadAppSettings(config)
        Catch err As Exception
            Console.WriteLine(err.ToString())
        End Try

    End Sub 'UpdateConfiguration
    
    
    ' Update the configuration file using the credentials
    ' of the passed user,  then call the routine that reads 
    ' the configuration settings.
    ' Note that the system issues an error if the user
    ' does not have administrative privileges on the server.
    Public Overloads Shared Sub UpdateConfiguration(ByVal _
        machineName As String, ByVal userName As String, ByVal _
        password As String)
        Try
            Console.WriteLine("MachineName:  [{0}]", machineName)
            Console.WriteLine("UserName:  [{0}]", userName)
            Console.WriteLine("Password:  [{0}]", password)

            ' Get the configuration.
            Dim config As Configuration = _
                WebConfigurationManager.OpenWebConfiguration("/", _
                "Default Web Site", Nothing, machineName, _
                userName, password)


            ' Add a new key/value pair to appSettings
            Dim count As String = _
                config.AppSettings.Settings.Count.ToString()
            config.AppSettings.Settings.Add("key_" + _
                count, "value_" + count)
            ' Save to the file,
            config.Save()

            ' Read the new appSettings.
            ReadAppSettings(config)

        Catch err As Exception
            Console.WriteLine(err.ToString())
        End Try

    End Sub 'UpdateConfiguration
    
    
    ' Read the appSettings on the remote server.
    Public Shared Sub ReadAppSettings(ByVal config As Configuration) 
        Try
            Console.WriteLine("--- Printing appSettings at [{0}] ---", _
                config.FilePath)
            Console.WriteLine("Count: [{0}]", _
                config.AppSettings.Settings.Count)
            Dim key As String
            For Each key In  config.AppSettings.Settings.AllKeys
                Console.WriteLine("  [{0}] = [{1}]", _
                    key, config.AppSettings.Settings(key).Value)
            Next key
            Console.WriteLine()
        
        Catch err As Exception
            Console.WriteLine(err.ToString())
        End Try
    
    End Sub 'ReadAppSettings
End Class 'RemoteConfiguration
using System;
using System.Configuration;
using System.Web.Configuration;
using System.Collections.Specialized;

namespace Samples.AspNet
{
    // This example dDemonstrates how to access and modify remote 
   // configuration files
    public class RemoteConfiguration
    {

        // The application entry point.
        public static void Main(string[] args)
        {
            // This string  contains the name of 
            // the remote server.
            string machineName = string.Empty;

            // Get the user's input.
            if (args.Length > 0)
            {
                // Get the name of the remote server.
                // The machine name must be in the format
                // accepted by the operating system.
                machineName = args[0];

                // Get the user name and password.
                if (args.Length > 1)     
                {                
                    string userName = args[1];
                    string password = string.Empty;
                    if (args.Length > 2)
                        password = args[2];

                    // Update the site configuration.
                    UpdateConfiguration(machineName, userName, 
                        password);
                }
                else
                { 
                    // Update the site configuration.
                    UpdateConfiguration(machineName);
                }
            }
            else
            {
                Console.WriteLine("Enter a valid server name.");
            }
        }

        // Update the configuration file using the credentials
        // of the user running this application then
        // call the routine that reads the configuration 
        // settings.
        // Note that the system issues an error if the user
        // does not have administrative privileges on the server.
        public static void UpdateConfiguration(string machineName)
        {
            try
            {
                Console.WriteLine("MachineName:  [{0}]", machineName);
                Console.WriteLine("UserDomainName:  [{0}]", 
                    Environment.UserDomainName);
                Console.WriteLine("UserName:  [{0}]", 
                    Environment.UserName);

                // Get the configuration.
                Configuration config = 
                    WebConfigurationManager.OpenWebConfiguration(
                    "/", "Default Web Site", null, machineName);
                
                // Add a new key/value pair to appSettings.
                string count = 
                    config.AppSettings.Settings.Count.ToString();
                config.AppSettings.Settings.Add("key_" + count, "value_" + count);
                // Save to the file,
                config.Save();
                
                // Read the new appSettings.
                ReadAppSettings(config);
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
        }

         // Update the configuration file using the credentials
         // of the passed user. Tthen,
     // call the routine that reads the configuration settings.
        // Note that the system issues an error if the user
        // does not have administrative privileges on the server.
        public static void UpdateConfiguration(string machineName, 
            string userName, string password)
        {
            try
            {
                Console.WriteLine("MachineName:  [{0}]", machineName);
                Console.WriteLine("UserName:  [{0}]", userName);
                Console.WriteLine("Password:  [{0}]", password);

                // Get the configuration.
                Configuration config = 
                    WebConfigurationManager.OpenWebConfiguration(
                    "/", "Default Web Site", null, 
                    machineName, userName, password);


                // Add a new key/value pair to appSettings
                string count =
                    config.AppSettings.Settings.Count.ToString();
                config.AppSettings.Settings.Add("key_" + count, "value_" + count);

             // Save changes to the file.
                config.Save();

                // Read the new appSettings.
                ReadAppSettings(config);
              
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
        }

        // Read the appSettings on the remote server.
        public static void ReadAppSettings(
            Configuration config)
        {
            try
            {
                Console.WriteLine("--- Printing appSettings at [{0}] ---", 
                    config.FilePath);
                Console.WriteLine("Count: [{0}]", 
                    config.AppSettings.Settings.Count);
                foreach (string key in config.AppSettings.Settings.AllKeys)
                {
                    Console.WriteLine("  [{0}] = [{1}]", 
                        key, config.AppSettings.Settings[key].Value);
                }
                Console.WriteLine();

            }           
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }
        }
    }

}

The previous code example reads and modifies the values of the appSettings element configured for the server's Default Web Site. The values are then displayed on the console.

The code uses the following methods:

  • OpenWebConfiguration, to open the Web application's configuration file as a Configuration object. Note that the implied user must have administrative privileges on the remote server.

  • OpenWebConfiguration, to open the Web application's configuration file as a Configuration object. Note that the user specified in the parameter list must have administrative privileges on the remote server.

  • AppSettings, to access the default site-related section.

  • GetSection, to access the default site identity section.

Compiling the Code

To compile the console application, you must use the following command.

vbc /out:RemoteConfiguration.exe /t:exe RemoteConfiguration.vb
/r:System.Web.dll /r:System.Configuration.dll
csc /out: RemoteConfiguration.exe /t:exe RemoteConfiguration.cs
/r:System.Web.dll /r:System.Configuration.dll

Security

To access a configuration file on a remote server, your application must have administrative privileges on that remote server.

NoteNote

This is a stricter requirement than the one needed to access local configuration files. To access local files, the application only needs read/write privileges, and read access to the IIS metabase to resolve the path.

See Also

Reference

ASP.NET IIS Registration Tool (Aspnet_regiis.exe)
System.Configuration
System.Web.Configuration

Concepts

Editing ASP.NET Remote Configuration Files
Using the Configuration Classes
ASP.NET Configuration Overview
How-to Topics — Configuring ASP.NET Applications

Other Resources

Configuring Applications