WebConfigurationManager.OpenWebConfiguration Метод

Определение

Открывает файл конфигурации веб-приложения в качестве Configuration объекта.

Перегрузки

Имя Описание
OpenWebConfiguration(String)

Открывает файл конфигурации веб-приложения в качестве объекта, используя указанный виртуальный Configuration путь для разрешения операций чтения или записи.

OpenWebConfiguration(String, String)

Открывает файл конфигурации веб-приложения в качестве объекта, используя указанный виртуальный Configuration путь и имя сайта, чтобы разрешить операции чтения или записи.

OpenWebConfiguration(String, String, String)

Открывает файл конфигурации веб-приложения в качестве объекта, используя указанный виртуальный Configuration путь, имя сайта и расположение, чтобы разрешить операции чтения или записи.

OpenWebConfiguration(String, String, String, String)

Открывает файл конфигурации веб-приложения в качестве объекта, используя указанный Configuration виртуальный путь, имя сайта, расположение и сервер, чтобы разрешить операции чтения или записи.

OpenWebConfiguration(String, String, String, String, IntPtr)

Открывает файл конфигурации веб-приложения в качестве Configuration объекта с помощью указанного виртуального пути, имени сайта, расположения, сервера и контекста безопасности для разрешения операций чтения или записи.

OpenWebConfiguration(String, String, String, String, String, String)

Открывает файл конфигурации веб-приложения в качестве Configuration объекта с помощью указанного виртуального пути, имени сайта, расположения, сервера и контекста безопасности для разрешения операций чтения или записи.

OpenWebConfiguration(String)

Открывает файл конфигурации веб-приложения в качестве объекта, используя указанный виртуальный Configuration путь для разрешения операций чтения или записи.

public:
 static System::Configuration::Configuration ^ OpenWebConfiguration(System::String ^ path);
public static System.Configuration.Configuration OpenWebConfiguration(string path);
static member OpenWebConfiguration : string -> System.Configuration.Configuration
Public Shared Function OpenWebConfiguration (path As String) As Configuration

Параметры

path
String

Виртуальный путь к файлу конфигурации. Если nullкорневой Web.config файл открыт.

Возвращаемое значение

Объект Configuration.

Исключения

Не удалось загрузить допустимый файл конфигурации.

Примеры

В следующем примере показано, как получить доступ к сведениям о конфигурации с OpenWebConfiguration помощью метода.


// Show how to use OpenWebConfiguration(string).
// It gets he appSettings section of a Web application
// runnig on the local server.
static void OpenWebConfiguration1()
{
    // Get the configuration object for a Web application
    // running on the local server.
    System.Configuration.Configuration config =
        WebConfigurationManager.OpenWebConfiguration("/configTest")
        as System.Configuration.Configuration;

    // Get the appSettings.
    KeyValueConfigurationCollection appSettings =
         config.AppSettings.Settings;

    // Loop through the collection and
    // display the appSettings key, value pairs.
    Console.WriteLine("[appSettings for app at: {0}]", "/configTest");
    foreach (string key in appSettings.AllKeys)
    {
        Console.WriteLine("Name: {0} Value: {1}",
        key, appSettings[key].Value);
    }

    Console.WriteLine();
}
' Show how to use OpenWebConfiguration(string).
' It gets he appSettings section of a Web application 
' runnig on the local server. 
Shared Sub OpenWebConfiguration1()
   ' Get the configuration object for a Web application
   ' running on the local server. 
     Dim config As System.Configuration.Configuration = _
     WebConfigurationManager.OpenWebConfiguration("/configTest")
   
   ' Get the appSettings.
     Dim appSettings As KeyValueConfigurationCollection = _
     config.AppSettings.Settings
   
   
   ' Loop through the collection and
   ' display the appSettings key, value pairs.
   Console.WriteLine("[appSettings for app at: {0}]", "/configTest")
   Dim key As String
   For Each key In  appSettings.AllKeys
         Console.WriteLine("Name: {0} Value: {1}", _
         key, appSettings(key).Value)
   Next key
   
   Console.WriteLine()
End Sub

Комментарии

Чтобы получить Configuration объект для ресурса, код должен иметь права на чтение всех файлов конфигурации, от которых он наследует параметры. Чтобы обновить файл конфигурации, код должен иметь дополнительные права записи как для файла конфигурации, так и для каталога, в котором он существует.

См. также раздел

Применяется к

OpenWebConfiguration(String, String)

Открывает файл конфигурации веб-приложения в качестве объекта, используя указанный виртуальный Configuration путь и имя сайта, чтобы разрешить операции чтения или записи.

public:
 static System::Configuration::Configuration ^ OpenWebConfiguration(System::String ^ path, System::String ^ site);
public static System.Configuration.Configuration OpenWebConfiguration(string path, string site);
static member OpenWebConfiguration : string * string -> System.Configuration.Configuration
Public Shared Function OpenWebConfiguration (path As String, site As String) As Configuration

Параметры

path
String

Виртуальный путь к файлу конфигурации.

site
String

Имя веб-сайта приложения, отображаемое в конфигурации Internet Information Services (IIS).

Возвращаемое значение

Объект Configuration.

Исключения

Не удалось загрузить допустимый файл конфигурации.

Примеры

В следующем примере показано, как получить доступ к сведениям о конфигурации с OpenWebConfiguration помощью метода.


// Show how to use OpenWebConfiguration(string, string).
// It gets he appSettings section of a Web application
// runnig on the local server.
static void OpenWebConfiguration2()
{
    // Get the configuration object for a Web application
    // running on the local server.
    System.Configuration.Configuration config =
        WebConfigurationManager.OpenWebConfiguration("/configTest",
        "Default Web Site")
        as System.Configuration.Configuration;

    // Get the appSettings.
    KeyValueConfigurationCollection appSettings =
         config.AppSettings.Settings;

    // Loop through the collection and
    // display the appSettings key, value pairs.
    Console.WriteLine(
        "[appSettings for app at: /configTest");
    Console.WriteLine(" and site: Default Web Site]");

    foreach (string key in appSettings.AllKeys)
    {
        Console.WriteLine("Name: {0} Value: {1}",
        key, appSettings[key].Value);
    }

    Console.WriteLine();
}
' Show how to use OpenWebConfiguration(string, string).
' It gets he appSettings section of a Web application 
' runnig on the local server. 
Shared Sub OpenWebConfiguration2()
   ' Get the configuration object for a Web application
   ' running on the local server. 
     Dim config As System.Configuration.Configuration = _
     WebConfigurationManager.OpenWebConfiguration( _
     "/configTest", "Default Web Site")
   
   ' Get the appSettings.
     Dim appSettings As KeyValueConfigurationCollection = _
     config.AppSettings.Settings
   
   
   ' Loop through the collection and
   ' display the appSettings key, value pairs.
   Console.WriteLine("[appSettings for app at: /configTest")
   Console.WriteLine(" and site: Default Web Site]")
   
   Dim key As String
   For Each key In  appSettings.AllKeys
         Console.WriteLine("Name: {0} Value: {1}", _
         key, appSettings(key).Value)
   Next key
   
   Console.WriteLine()
End Sub

Комментарии

Чтобы получить Configuration объект для ресурса, код должен иметь права на чтение всех файлов конфигурации, от которых он наследует параметры. Чтобы обновить файл конфигурации, код должен иметь дополнительные права записи как для файла конфигурации, так и для каталога, в котором он существует.

См. также раздел

Применяется к

OpenWebConfiguration(String, String, String)

Открывает файл конфигурации веб-приложения в качестве объекта, используя указанный виртуальный Configuration путь, имя сайта и расположение, чтобы разрешить операции чтения или записи.

public:
 static System::Configuration::Configuration ^ OpenWebConfiguration(System::String ^ path, System::String ^ site, System::String ^ locationSubPath);
public static System.Configuration.Configuration OpenWebConfiguration(string path, string site, string locationSubPath);
static member OpenWebConfiguration : string * string * string -> System.Configuration.Configuration
Public Shared Function OpenWebConfiguration (path As String, site As String, locationSubPath As String) As Configuration

Параметры

path
String

Виртуальный путь к файлу конфигурации.

site
String

Имя веб-сайта приложения, отображаемое в конфигурации Internet Information Services (IIS).

locationSubPath
String

Конкретный ресурс, к которому применяется конфигурация.

Возвращаемое значение

Объект Configuration.

Исключения

Не удалось загрузить допустимый файл конфигурации.

Примеры

В следующем примере показано, как получить доступ к сведениям о конфигурации с OpenWebConfiguration помощью метода.


// Show how to use OpenWebConfiguration(string, string, string).
// It gets he appSettings section of a Web application
// runnig on the local server.
static void OpenWebConfiguration3()
{
    // Get the configuration object for a Web application
    // running on the local server.
    System.Configuration.Configuration config =
        WebConfigurationManager.OpenWebConfiguration(
        "/configTest", "Default Web Site", null)
        as System.Configuration.Configuration;

    // Get the appSettings.
    KeyValueConfigurationCollection appSettings =
         config.AppSettings.Settings;

    // Loop through the collection and
    // display the appSettings key, value pairs.
    Console.WriteLine(
        "[appSettings for app at: /configTest");
    Console.WriteLine(" site: Default Web Site");
    Console.WriteLine(" and locationSubPath: null]");

    foreach (string key in appSettings.AllKeys)
    {
        Console.WriteLine("Name: {0} Value: {1}",
        key, appSettings[key].Value);
    }

    Console.WriteLine();
}
' Show how to use OpenWebConfiguration(string, string, string).
' It gets he appSettings section of a Web application 
' runnig on the local server. 
Shared Sub OpenWebConfiguration3()
   ' Get the configuration object for a Web application
   ' running on the local server. 
     Dim config As System.Configuration.Configuration = _
     WebConfigurationManager.OpenWebConfiguration( _
     "/configTest", "Default Web Site", Nothing)
   
   ' Get the appSettings.
     Dim appSettings As KeyValueConfigurationCollection = _
     config.AppSettings.Settings
   
   ' Loop through the collection and
   ' display the appSettings key, value pairs.
   Console.WriteLine("[appSettings for app at: /configTest")
   Console.WriteLine(" site: Default Web Site")
   Console.WriteLine(" and locationSubPath: null]")
   
   Dim key As String
   For Each key In  appSettings.AllKeys
         Console.WriteLine("Name: {0} Value: {1}", _
         key, appSettings(key).Value)
   Next key
   
   Console.WriteLine()
End Sub

Комментарии

Чтобы получить Configuration объект для ресурса, код должен иметь права на чтение всех файлов конфигурации, от которых он наследует параметры. Чтобы обновить файл конфигурации, код должен иметь дополнительные права записи как для файла конфигурации, так и для каталога, в котором он существует.

См. также раздел

Применяется к

OpenWebConfiguration(String, String, String, String)

Открывает файл конфигурации веб-приложения в качестве объекта, используя указанный Configuration виртуальный путь, имя сайта, расположение и сервер, чтобы разрешить операции чтения или записи.

public:
 static System::Configuration::Configuration ^ OpenWebConfiguration(System::String ^ path, System::String ^ site, System::String ^ locationSubPath, System::String ^ server);
public static System.Configuration.Configuration OpenWebConfiguration(string path, string site, string locationSubPath, string server);
static member OpenWebConfiguration : string * string * string * string -> System.Configuration.Configuration
Public Shared Function OpenWebConfiguration (path As String, site As String, locationSubPath As String, server As String) As Configuration

Параметры

path
String

Виртуальный путь к файлу конфигурации.

site
String

Имя веб-сайта приложения, отображаемое в конфигурации Internet Information Services (IIS).

locationSubPath
String

Конкретный ресурс, к которому применяется конфигурация.

server
String

Сетевое имя сервера, на котором находится веб-приложение.

Возвращаемое значение

Объект Configuration.

Исключения

Недопустимый параметр сервера.

Не удалось загрузить допустимый файл конфигурации.

Примеры

В следующем примере показано, как получить доступ к сведениям о конфигурации с OpenWebConfiguration помощью метода.


// Show how to use OpenWebConfiguration(string, string,
// string, string).
// It gets he appSettings section of a Web application
// running on the specified server.
// If the server is remote your application must have the
// required access rights to the configuration file.
static void OpenWebConfiguration4()
{
    // Get the configuration object for a Web application
    // running on the specified server.
    // Null for the subPath signifies no subdir.
    System.Configuration.Configuration config =
           WebConfigurationManager.OpenWebConfiguration(
            "/configTest", "Default Web Site", null, "myServer")
           as System.Configuration.Configuration;

    // Get the appSettings.
    KeyValueConfigurationCollection appSettings =
         config.AppSettings.Settings;

    // Loop through the collection and
    // display the appSettings key, value pairs.
    Console.WriteLine("[appSettings for Web app on server: myServer]");
    foreach (string key in appSettings.AllKeys)
    {
        Console.WriteLine("Name: {0} Value: {1}",
        key, appSettings[key].Value);
    }

    Console.WriteLine();
}
' Show how to use OpenWebConfiguration(string, string, 
' string, string).
' It gets he appSettings section of a Web application 
' running on the specified server. 
' If the server is remote your application must have the
' required access rights to the configuration file. 
Shared Sub OpenWebConfiguration4()
   ' Get the configuration object for a Web application
   ' running on the specified server.
   ' Null for the subPath signifies no subdir. 
   Dim config As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration("/configTest", "Default Web Site", Nothing, "myServer")
   
   ' Get the appSettings.
   Dim appSettings As KeyValueConfigurationCollection = config.AppSettings.Settings
   
   
   ' Loop through the collection and
   ' display the appSettings key, value pairs.
   Console.WriteLine("[appSettings for Web app on server: myServer]")
   Dim key As String
   For Each key In  appSettings.AllKeys
      Console.WriteLine("Name: {0} Value: {1}", key, appSettings(key).Value)
   Next key
   
   Console.WriteLine()
End Sub

Комментарии

Чтобы получить Configuration объект для удаленного ресурса, код должен иметь права администратора на удаленном компьютере.

См. также раздел

Применяется к

OpenWebConfiguration(String, String, String, String, IntPtr)

Открывает файл конфигурации веб-приложения в качестве Configuration объекта с помощью указанного виртуального пути, имени сайта, расположения, сервера и контекста безопасности для разрешения операций чтения или записи.

public:
 static System::Configuration::Configuration ^ OpenWebConfiguration(System::String ^ path, System::String ^ site, System::String ^ locationSubPath, System::String ^ server, IntPtr userToken);
public static System.Configuration.Configuration OpenWebConfiguration(string path, string site, string locationSubPath, string server, IntPtr userToken);
static member OpenWebConfiguration : string * string * string * string * nativeint -> System.Configuration.Configuration
Public Shared Function OpenWebConfiguration (path As String, site As String, locationSubPath As String, server As String, userToken As IntPtr) As Configuration

Параметры

path
String

Виртуальный путь к файлу конфигурации.

site
String

Имя веб-сайта приложения, отображаемое в конфигурации Internet Information Services (IIS).

locationSubPath
String

Конкретный ресурс, к которому применяется конфигурация.

server
String

Сетевое имя сервера, на котором находится веб-приложение.

userToken
IntPtr

nativeint

Маркер учетной записи для использования.

Возвращаемое значение

Объект Configuration.

Исключения

Недопустимые server параметры или userToken параметры.

Не удалось загрузить допустимый файл конфигурации.

Примеры

В следующем примере показано, как использовать OpenWebConfiguration метод для доступа к сведениям о конфигурации.


// Show how to use OpenWebConfiguration(string, string,
// string, string, IntPtr).
// It gets he appSettings section of a Web application
// running on a remote server.
// If the serve is remote your application shall have the
// requires access rights to the configuration file.
static void OpenWebConfiguration6()
{

    IntPtr userToken =
        System.Security.Principal.WindowsIdentity.GetCurrent().Token;

    string user =
        System.Security.Principal.WindowsIdentity.GetCurrent().Name;

    // Get the configuration object for a Web application
    // running on a remote server.
    System.Configuration.Configuration config =
        WebConfigurationManager.OpenWebConfiguration(
        "/configTest", "Default Web Site", null,
        "myServer", userToken) as System.Configuration.Configuration;

    // Get the appSettings.
    KeyValueConfigurationCollection appSettings =
         config.AppSettings.Settings;

    // Loop through the collection and
    // display the appSettings key, value pairs.
    Console.WriteLine(
        "[appSettings for Web app on server: myServer user: {0}]", user);
    foreach (string key in appSettings.AllKeys)
    {
        Console.WriteLine("Name: {0} Value: {1}",
        key, appSettings[key].Value);
    }

    Console.WriteLine();
}
' Show how to use OpenWebConfiguration(string, string, 
' string, string, IntPtr).
' It gets he appSettings section of a Web application 
' running on a remote server. 
' If the serve is remote your application shall have the
' requires access rights to the configuration file. 
Shared Sub OpenWebConfiguration6()
   
     Dim userToken As IntPtr = _
     System.Security.Principal.WindowsIdentity.GetCurrent().Token
   
     Dim user As String = _
     System.Security.Principal.WindowsIdentity.GetCurrent().Name
   
   ' Get the configuration object for a Web application
   ' running on a remote server.
     Dim config As System.Configuration.Configuration = _
     WebConfigurationManager.OpenWebConfiguration( _
     "/configTest", "Default Web Site", _
     Nothing, "myServer", userToken)
   
   ' Get the appSettings.
     Dim appSettings As KeyValueConfigurationCollection = _
     config.AppSettings.Settings
   
   ' Loop through the collection and
   ' display the appSettings key, value pairs.
     Console.WriteLine( _
     "[appSettings for Web app on server: myServer user: {0}]", user)
   Dim key As String
   For Each key In  appSettings.AllKeys
         Console.WriteLine("Name: {0} Value: {1}", _
         key, appSettings(key).Value)
   Next key
   
   Console.WriteLine()
End Sub

Комментарии

Этот метод используется для доступа к файлу конфигурации с помощью олицетворения.

Note

Маркер учетной записи обычно извлекается из экземпляра класса WindowsIdentity или через вызов неуправляемого кода, например вызов API Windows LogonUser. Дополнительные сведения о вызовах неуправляемого кода см. в разделе "Использование неуправляемых функций DLL".

Чтобы получить Configuration объект для удаленного ресурса, код должен иметь права администратора на удаленном компьютере.

См. также раздел

Применяется к

OpenWebConfiguration(String, String, String, String, String, String)

Открывает файл конфигурации веб-приложения в качестве Configuration объекта с помощью указанного виртуального пути, имени сайта, расположения, сервера и контекста безопасности для разрешения операций чтения или записи.

public:
 static System::Configuration::Configuration ^ OpenWebConfiguration(System::String ^ path, System::String ^ site, System::String ^ locationSubPath, System::String ^ server, System::String ^ userName, System::String ^ password);
public static System.Configuration.Configuration OpenWebConfiguration(string path, string site, string locationSubPath, string server, string userName, string password);
static member OpenWebConfiguration : string * string * string * string * string * string -> System.Configuration.Configuration
Public Shared Function OpenWebConfiguration (path As String, site As String, locationSubPath As String, server As String, userName As String, password As String) As Configuration

Параметры

path
String

Виртуальный путь к файлу конфигурации.

site
String

Имя веб-сайта приложения, отображаемое в конфигурации Internet Information Services (IIS).

locationSubPath
String

Конкретный ресурс, к которому применяется конфигурация.

server
String

Сетевое имя сервера, на котором находится веб-приложение.

userName
String

Полное имя пользователя (домен\пользователь), используемое при открытии файла.

password
String

Пароль для имени пользователя.

Возвращаемое значение

Объект Configuration.

Исключения

Недопустимые server или userNamepassword параметры.

Не удалось загрузить допустимый файл конфигурации.

Примеры

В следующем примере показано, как получить доступ к сведениям о конфигурации с OpenWebConfiguration помощью метода.


// Show how to use OpenWebConfiguration(string, string,
// string, string, string, string).
// It gets he appSettings section of a Web application
// running on a remote server.
// If the server is remote your application must have the
// required access rights to the configuration file.
static void OpenWebConfiguration5()
{
    // Get the current user.
    string user =
        System.Security.Principal.WindowsIdentity.GetCurrent().Name;

    // Assign the actual password.
    string password = "userPassword";

    // Get the configuration object for a Web application
    // running on a remote server.
    System.Configuration.Configuration config =
        WebConfigurationManager.OpenWebConfiguration(
        "/configTest", "Default Web Site", null, "myServer",
        user, password) as System.Configuration.Configuration;

    // Get the appSettings.
    KeyValueConfigurationCollection appSettings =
         config.AppSettings.Settings;

    // Loop through the collection and
    // display the appSettings key, value pairs.
    Console.WriteLine(
        "[appSettings for Web app on server: myServer user: {0}]", user);
    foreach (string key in appSettings.AllKeys)
    {
        Console.WriteLine("Name: {0} Value: {1}",
        key, appSettings[key].Value);
    }

    Console.WriteLine();
}
' Show how to use OpenWebConfiguration(string, string, 
' string, string, string, string).
' It gets he appSettings section of a Web application 
' running on a remote server. 
' If the server is remote your application must have the
' required access rights to the configuration file. 
Shared Sub OpenWebConfiguration5()
   ' Get the current user.
     Dim user As String = _
     System.Security.Principal.WindowsIdentity.GetCurrent().Name
   
   ' Assign the actual password.
   Dim password As String = "userPassword"
   
   ' Get the configuration object for a Web application
   ' running on a remote server.
     Dim config As System.Configuration.Configuration = _
     WebConfigurationManager.OpenWebConfiguration( _
     "/configTest", "Default Web Site", _
     Nothing, "myServer", user, password)
   
   ' Get the appSettings.
     Dim appSettings As KeyValueConfigurationCollection = _
     config.AppSettings.Settings
   
   
   ' Loop through the collection and
   ' display the appSettings key, value pairs.
     Console.WriteLine( _
     "[appSettings for Web app on server: myServer user: {0}]", user)
   Dim key As String
   For Each key In  appSettings.AllKeys
         Console.WriteLine("Name: {0} Value: {1}", _
         key, appSettings(key).Value)
   Next key
   
   Console.WriteLine()
End Sub

Комментарии

Этот метод используется для доступа к файлу конфигурации с помощью олицетворения.

Чтобы получить Configuration объект для удаленного ресурса, код должен иметь права администратора на удаленном компьютере.

Возможно, потребуется запустить средство регистрации ASP.NET IIS (Aspnet_regiis.exe) с параметром -config+, чтобы включить доступ к файлам конфигурации на удаленном компьютере.

См. также раздел

Применяется к