ResourceReader Конструкторы

Определение

Инициализирует новый экземпляр класса ResourceReader.

Перегрузки

Имя Описание
ResourceReader(Stream)

Инициализирует новый экземпляр класса для указанного ResourceReader потока.

ResourceReader(String)

Инициализирует новый экземпляр класса для указанного ResourceReader именованного файла ресурсов.

Комментарии

Important

Использование экземпляра этого типа с ненадежными данными является угрозой безопасности. Используйте этот объект только с доверенными данными. Дополнительные сведения см. в разделе Проверка всех входных данных.

ResourceReader(Stream)

Исходный код:
ResourceReader.cs
Исходный код:
ResourceReader.cs
Исходный код:
ResourceReader.cs
Исходный код:
ResourceReader.cs
Исходный код:
ResourceReader.cs

Инициализирует новый экземпляр класса для указанного ResourceReader потока.

public:
 ResourceReader(System::IO::Stream ^ stream);
public ResourceReader(System.IO.Stream stream);
[System.Security.SecurityCritical]
public ResourceReader(System.IO.Stream stream);
new System.Resources.ResourceReader : System.IO.Stream -> System.Resources.ResourceReader
[<System.Security.SecurityCritical>]
new System.Resources.ResourceReader : System.IO.Stream -> System.Resources.ResourceReader
Public Sub New (stream As Stream)

Параметры

stream
Stream

Входной поток для чтения ресурсов.

Атрибуты

Исключения

Параметр stream недоступен для чтения.

Параметр stream имеет значение null.

При доступе произошла ошибка ввода-вывода stream.

Примеры

В этом разделе используется следующий файл .txt с именем для PatientForm.txt определения ресурсов, используемых приложением.

Title="Top Pet Animal Clinic"
Label1="Patient Number:"
Label2="Pet Name:"
Label3="Species:"
Label4="Breed:"
Label5="Date of Birth:"
Label6="Age:"
Label7="Owner:"
Label8="Address:"
Label9="Home Phone:"
Label10="Work Phone:"
Label11="Mobile Phone:"

Вы можете скомпилировать файл .txt в файл ресурсов, выполнив следующую команду:

resgen PatientForm.txt

В следующем примере предполагается, что файл ресурсов внедрен в сборку, содержащую исполняемый код приложения. Он извлекает файл ресурсов с именем PatientForm.resources из текущих выполняемых сборок и отображает имя и значение каждого из его ресурсов.

using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Resources;

public class Example
{
   public static void Main()
   {
      var assem = typeof(Example).Assembly;
      var fs = assem.GetManifestResourceStream("PatientForm.resources");
      var rr = new ResourceReader(fs);
      IDictionaryEnumerator dict = rr.GetEnumerator();
      int ctr = 0;

      while (dict.MoveNext()) {
         ctr++;
         Console.WriteLine("{0:00}: {1} = {2}", ctr, dict.Key, dict.Value);
      }
      rr.Close();
   }
}
// The example displays the following output:
//       01: Label3 = "Species:"
//       02: Label2 = "Pet Name:"
//       03: Label1 = "Patient Number:"
//       04: Label7 = "Owner:"
//       05: Label6 = "Age:"
//       06: Label5 = "Date of Birth:"
//       07: Label4 = "Breed:"
//       08: Label9 = "Home Phone:"
//       09: Label8 = "Address:"
//       10: Title = "Top Pet Animal Clinic"
//       11: Label10 = "Work Phone:"
//       12: Label11 = "Mobile Phone:"
Imports System.Collections
Imports System.IO
Imports System.Reflection
Imports System.Resources

Module Example
   Public Sub Main()
      Dim assem As Assembly = GetType(Example).Assembly
      Dim fs As Stream = assem.GetManifestResourceStream("PatientForm.resources")
      Dim rr As New ResourceReader(fs)
      Dim dict As IDictionaryEnumerator = rr.GetEnumerator
      Dim ctr As Integer

      Do While dict.MoveNext()
         ctr += 1
         Console.WriteLine("{0:00}: {1} = {2}", ctr, dict.Key, dict.Value)
      Loop

      rr.Close()
   End Sub
End Module
' The example displays the following output:
'       01: Label3 = "Species:"
'       02: Label2 = "Pet Name:"
'       03: Label1 = "Patient Number:"
'       04: Label7 = "Owner:"
'       05: Label6 = "Age:"
'       06: Label5 = "Date of Birth:"
'       07: Label4 = "Breed:"
'       08: Label9 = "Home Phone:"
'       09: Label8 = "Address:"
'       10: Title = "Top Pet Animal Clinic"
'       11: Label10 = "Work Phone:"
'       12: Label11 = "Mobile Phone:"

Если называется Example.csпример C#, его можно скомпилировать с помощью следующей команды:

csc Example.cs /res:PatientForm.resources

Если пример Visual Basic называется Example.vb, его можно скомпилировать с помощью следующей команды:

vbc Example.vb /res:PatientForm.resources

Комментарии

Конструктор ResourceReader(Stream) создает экземпляр ResourceReader объекта, который извлекает ресурсы из автономного файла ресурсов или из файла ресурсов .resources, внедренного в сборку. Чтобы прочитать из автономного файла ресурсов, создайте Stream экземпляр объекта и передайте его конструктору ResourceReader(Stream) . Чтобы прочитать из внедренного файла ресурсов, вызовите Assembly.GetManifestResourceStream метод с именем файла resources с учетом регистра и передайте возвращенный Stream объект конструктору ResourceReader(Stream) .

Important

Использование экземпляра этого типа с ненадежными данными является угрозой безопасности. Используйте этот объект только с доверенными данными. Дополнительные сведения см. в разделе Проверка всех входных данных.

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

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

ResourceReader(String)

Исходный код:
ResourceReader.cs
Исходный код:
ResourceReader.cs
Исходный код:
ResourceReader.cs
Исходный код:
ResourceReader.cs
Исходный код:
ResourceReader.cs

Инициализирует новый экземпляр класса для указанного ResourceReader именованного файла ресурсов.

public:
 ResourceReader(System::String ^ fileName);
public ResourceReader(string fileName);
new System.Resources.ResourceReader : string -> System.Resources.ResourceReader
Public Sub New (fileName As String)

Параметры

fileName
String

Путь и имя файла ресурса для чтения. filename не учитывает регистр.

Исключения

Параметр fileName имеет значение null.

Не удается найти файл.

Произошла ошибка ввода-вывода.

Файл ресурса имеет недопустимый формат. Например, длина файла может быть нулевой.

Примеры

В этом разделе используется следующий файл .txt с именем для PatientForm.txt определения ресурсов, используемых приложением.

Title="Top Pet Animal Clinic"
Label1="Patient Number:"
Label2="Pet Name:"
Label3="Species:"
Label4="Breed:"
Label5="Date of Birth:"
Label6="Age:"
Label7="Owner:"
Label8="Address:"
Label9="Home Phone:"
Label10="Work Phone:"
Label11="Mobile Phone:"

Этот файл .txt можно скомпилировать в файл resources, выполнив следующую команду:

resgen PatientForm.txt

В следующем примере перечисляются ресурсы PatientForm.resources и отображаются имя и значение каждого.

using System;
using System.Collections;
using System.Resources;

public class Example
{
   public static void Main()
   {
      var rr = new ResourceReader("PatientForm.resources");
      IDictionaryEnumerator dict = rr.GetEnumerator();
      int ctr = 0;

      while (dict.MoveNext()) {
         ctr++;
         Console.WriteLine("{0:00}: {1} = {2}", ctr, dict.Key, dict.Value);
      }

      rr.Close();
   }
}
// The example displays the following output:
//       01: Label3 = "Species:"
//       02: Label2 = "Pet Name:"
//       03: Label1 = "Patient Number:"
//       04: Label7 = "Owner:"
//       05: Label6 = "Age:"
//       06: Label5 = "Date of Birth:"
//       07: Label4 = "Breed:"
//       08: Label9 = "Home Phone:"
//       09: Label8 = "Address:"
//       10: Title = "Top Pet Animal Clinic"
//       11: Label10 = "Work Phone:"
//       12: Label11 = "Mobile Phone:"
Imports System.Collections
Imports System.Resources

Module Example
   Public Sub Main()
      Dim rr As New ResourceReader("PatientForm.resources")
      Dim dict As IDictionaryEnumerator = rr.GetEnumerator
      Dim ctr As Integer

      Do While dict.MoveNext()
         ctr += 1
         Console.WriteLine("{0:00}: {1} = {2}", ctr, dict.Key, dict.Value)
      Loop
      
      rr.Close()
   End Sub
End Module
' The example displays the following output:
'       01: Label3 = "Species:"
'       02: Label2 = "Pet Name:"
'       03: Label1 = "Patient Number:"
'       04: Label7 = "Owner:"
'       05: Label6 = "Age:"
'       06: Label5 = "Date of Birth:"
'       07: Label4 = "Breed:"
'       08: Label9 = "Home Phone:"
'       09: Label8 = "Address:"
'       10: Title = "Top Pet Animal Clinic"
'       11: Label10 = "Work Phone:"
'       12: Label11 = "Mobile Phone:"

Комментарии

Конструктор ResourceReader(String) создает экземпляр ResourceReader объекта, который извлекает ресурсы из автономного файла ресурсов. Чтобы получить ресурсы из внедренного файла РЕСУРСОВ, используйте ResourceReader(Stream) конструктор.

Important

Использование экземпляра этого типа с ненадежными данными является угрозой безопасности. Используйте этот объект только с доверенными данными. Дополнительные сведения см. в разделе Проверка всех входных данных.

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