ResXResourceReader Klasa

Definicja

Wylicza pliki i strumienie zasobów XML (resx) oraz odczytuje sekwencyjną nazwę zasobu i pary wartości.

public ref class ResXResourceReader : System::Resources::IResourceReader
public ref class ResXResourceReader : IDisposable, System::Collections::IEnumerable, System::Resources::IResourceReader
public class ResXResourceReader : System.Resources.IResourceReader
public class ResXResourceReader : IDisposable, System.Collections.IEnumerable, System.Resources.IResourceReader
type ResXResourceReader = class
    interface IResourceReader
    interface IEnumerable
    interface IDisposable
Public Class ResXResourceReader
Implements IResourceReader
Public Class ResXResourceReader
Implements IDisposable, IEnumerable, IResourceReader
Dziedziczenie
ResXResourceReader
Implementuje

Przykłady

W poniższym przykładzie pokazano, jak używać metody ResXResourceReader do iterowania zasobów w pliku resx. ResXResourceReaderrsxr Najpierw element jest tworzony dla pliku items.resx. GetEnumerator Następnie metoda służy do tworzenia elementu IDictionaryEnumerator w celu iterowania zasobów i wyświetlania zawartości w konsoli.

#using <system.windows.forms.dll>
#using <System.dll>

using namespace System;
using namespace System::Resources;
using namespace System::Collections;
void main()
{

   // Create a ResXResourceReader for the file items.resx.
   ResXResourceReader^ rsxr = gcnew ResXResourceReader( "items.resx" );


   // Iterate through the resources and display the contents to the console.
   IEnumerator^ myEnum = rsxr->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum->Current);
      Console::WriteLine( "{0}:\t {1}", d->Key, d->Value );
   }


   //Close the reader.
   rsxr->Close();
}
using System;
using System.Resources;
using System.Collections;

class ReadResXResources
{
   public static void Main()
   {

      // Create a ResXResourceReader for the file items.resx.
      ResXResourceReader rsxr = new ResXResourceReader("items.resx");

      // Iterate through the resources and display the contents to the console.
      foreach (DictionaryEntry d in rsxr)
      {
    Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
      }

     //Close the reader.
     rsxr.Close();
   }
}
Imports System.Resources
Imports System.Collections

Class ReadResXResources
   
   Public Shared Sub Main()
      
      ' Create a ResXResourceReader for the file items.resx.
      Dim rsxr As ResXResourceReader
      rsxr = New ResXResourceReader("items.resx")

      ' Iterate through the resources and display the contents to the console.
      Dim d As DictionaryEntry
      For Each d In  rsxr
         Console.WriteLine(d.Key.ToString() + ":" + ControlChars.Tab + d.Value.ToString())
      Next d
      
      'Close the reader.
      rsxr.Close()

   End Sub

End Class

Uwagi

Ważne

Wywoływanie metod z tej klasy z niezaufanymi danymi jest zagrożeniem bezpieczeństwa. Wywołaj metody z tej klasy tylko z zaufanymi danymi. Aby uzyskać więcej informacji, zobacz Validate All Inputs (Weryfikowanie wszystkich danych wejściowych).

Klasa ResXResourceReader udostępnia domyślną implementację interfejsu IResourceReader , który odczytuje informacje o zasobach w formacie XML. Aby odczytać informacje o zasobie z formatu zasobu binarnego, użyj ResourceReader klasy .

Klasa służy ResXResourceReader do wyliczania zasobów w plikach resx przez przechodzenie przez moduł wyliczający słownika (IDictionaryEnumerator), który jest zwracany przez metodę GetEnumerator . Metody podane przez IDictionaryEnumerator usługę umożliwiają przejście do następnego zasobu i odczytanie nazwy i wartości każdego zasobu w pliku resx.

Uwaga

Klasa ResXResourceReader udostępnia dwa moduły wyliczania. Metoda ResXResourceReader.GetEnumerator zwraca IDictionaryEnumerator obiekt. Zalecamy użycie tej metody do wyliczania zasobów. Metoda ResXResourceReader.IEnumerable.GetEnumerator jest jawną implementacją interfejsu, która zwraca IEnumerator obiekt; nie zalecamy jego użycia.

W poniższym przykładzie GetEnumerator użyto metody w celu uzyskania obiektu używanego IDictionaryEnumerator do wyliczania zasobów w pliku resx. Przykład zawiera procedurę CreateResourceFile , która tworzy niezbędny plik zasobów.

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

public class Example
{
   private const string resxFilename = @".\CountryHeaders.resx";
    
   public static void Main()
   {
      // Create a resource file to read.
      CreateResourceFile();
      
      // Enumerate the resources in the file.
      ResXResourceReader rr = new ResXResourceReader(resxFilename);
      IDictionaryEnumerator dict = rr.GetEnumerator();
      while (dict.MoveNext())
         Console.WriteLine("{0}: {1}", dict.Key, dict.Value);   
   }

   private static void CreateResourceFile()
   {
      ResXResourceWriter rw = new ResXResourceWriter(resxFilename);
      string[] resNames = {"Country", "Population", "Area", 
                           "Capital", "LCity" };
      string[] columnHeaders = { "Country Name", "Population (2010}", 
                                 "Area", "Capital", "Largest City" };
      string[] comments = { "The localized country name", "", 
                            "The area in square miles", "", 
                            "The largest city based on 2010 data" };
      rw.AddResource("Title", "Country Information");
      rw.AddResource("nColumns", resNames.Length);
      for (int ctr = 0; ctr < resNames.Length; ctr++) {
         ResXDataNode node = new ResXDataNode(resNames[ctr], columnHeaders[ctr]);
         node.Comment = comments[ctr];
         rw.AddResource(node);
      }
      rw.Generate();
      rw.Close();
   }
}
// The example displays the following output:
//       Title: Country Information
//       nColumns: 5
//       Country: Country Name
//       Population: Population (2010}
//       Area: Area
//       Capital: Capital
//       LCity: Largest City
Imports System.Collections
Imports System.Resources

Module Example
   Private Const resxFilename As String = ".\CountryHeaders.resx"
     
   Public Sub Main()
      ' Create a resource file to read.
      CreateResourceFile()
      
      ' Enumerate the resources in the file.
      Dim rr As New ResXResourceReader(resxFilename)
      Dim dict As IDictionaryEnumerator = rr.GetEnumerator()
      Do While dict.MoveNext()
         Console.WriteLine("{0}: {1}", dict.Key, dict.Value)   
      Loop
   End Sub
   
   Private Sub CreateResourceFile()
      Dim rw As New ResxResourceWriter(resxFilename)
      Dim resNames() As String = {"Country", "Population", "Area", 
                                  "Capital", "LCity" }
      Dim columnHeaders() As String = { "Country Name", "Population (2010}", 
                                        "Area", "Capital", "Largest City" }
      Dim comments() As String = { "The localized country name", "", 
                                   "The area in square miles", "", 
                                   "The largest city based on 2010 data" }
      rw.AddResource("Title", "Country Information")
      rw.AddResource("nColumns", resNames.Length)
      For ctr As Integer = 0 To resNames.Length - 1
         Dim node As New ResXDataNode(resNames(ctr), columnHeaders(ctr))
         node.Comment = comments(ctr)
         rw.AddResource(node)
      Next
      rw.Generate()
      rw.Close()
   End Sub
End Module
' The example displays the following output:
'       Title: Country Information
'       nColumns: 5
'       Country: Country Name
'       Population: Population (2010}
'       Area: Area
'       Capital: Capital
'       LCity: Largest City

UseResXDataNodes Jeśli właściwość ma truewartość , wartość IDictionaryEnumerator.Value właściwości jest obiektemResXDataNode, a nie wartością zasobu. Dzięki temu komentarz elementu zasobu jest dostępny z ResXDataNode.Comment właściwości . Poniższy przykład ustawia UseResXDataNodes właściwość na true i wylicza zasoby w pliku resx.

using System;
using System.Collections;
using System.ComponentModel.Design;
using System.Resources;

public class Example
{
   private const string resxFilename = @".\CountryHeaders.resx";
    
   public static void Main()
   {
      // Create a resource file to read.
      CreateResourceFile();
      
      // Enumerate the resources in the file.
      ResXResourceReader rr = new ResXResourceReader(resxFilename);
      rr.UseResXDataNodes = true;
      IDictionaryEnumerator dict = rr.GetEnumerator();
      while (dict.MoveNext()) {
         ResXDataNode node = (ResXDataNode) dict.Value;
         Console.WriteLine("{0,-20} {1,-20} {2}", 
                           node.Name + ":", 
                           node.GetValue((ITypeResolutionService) null), 
                           ! String.IsNullOrEmpty(node.Comment) ? "// " + node.Comment : "");
      }
   }

   private static void CreateResourceFile()
   {
      ResXResourceWriter rw = new ResXResourceWriter(resxFilename);
      string[] resNames = {"Country", "Population", "Area", 
                           "Capital", "LCity" };
      string[] columnHeaders = { "Country Name", "Population (2010}", 
                                 "Area", "Capital", "Largest City" };
      string[] comments = { "The localized country name", "", 
                            "The area in square miles", "", 
                            "The largest city based on 2010 data" };
      rw.AddResource("Title", "Country Information");
      rw.AddResource("nColumns", resNames.Length);
      for (int ctr = 0; ctr < resNames.Length; ctr++) {
         ResXDataNode node = new ResXDataNode(resNames[ctr], columnHeaders[ctr]);
         node.Comment = comments[ctr];
         rw.AddResource(node);
      }
      rw.Generate();
      rw.Close();
   }
}
// The example displays the following output:
//    Title:               Country Information
//    nColumns:            5
//    Country:             Country Name         // The localized country name
//    Population:          Population (2010}
//    Area:                Area                 // The area in square miles
//    Capital:             Capital
//    LCity:               Largest City         // The largest city based on 2010 data
Imports System.Collections
Imports System.ComponentModel.Design
Imports System.Resources

Module Example
   Private Const resxFilename As String = ".\CountryHeaders.resx"
     
   Public Sub Main()
      ' Create a resource file to read.
      CreateResourceFile()
      
      ' Enumerate the resources in the file.
      Dim rr As New ResXResourceReader(resxFilename)
      rr.UseResXDataNodes = True
      Dim dict As IDictionaryEnumerator = rr.GetEnumerator()
      Do While dict.MoveNext()
         Dim node As ResXDataNode = DirectCast(dict.Value, ResXDataNode)
         Console.WriteLine("{0,-20} {1,-20} {2}", 
                           node.Name + ":", 
                           node.GetValue(CType(Nothing, ITypeResolutionService)), 
                           If(Not String.IsNullOrEmpty(node.Comment), "// " + node.Comment, ""))
      Loop
   End Sub
   
   Private Sub CreateResourceFile()
      Dim rw As New ResxResourceWriter(resxFilename)
      Dim resNames() As String = {"Country", "Population", "Area", 
                                  "Capital", "LCity" }
      Dim columnHeaders() As String = { "Country Name", "Population (2010}", 
                                        "Area", "Capital", "Largest City" }
      Dim comments() As String = { "The localized country name", "", 
                                   "The area in square miles", "", 
                                   "The largest city based on 2010 data" }
      rw.AddResource("Title", "Country Information")
      rw.AddResource("nColumns", resNames.Length)
      For ctr As Integer = 0 To resNames.Length - 1
         Dim node As New ResXDataNode(resNames(ctr), columnHeaders(ctr))
         node.Comment = comments(ctr)
         rw.AddResource(node)
      Next
      rw.Generate()
      rw.Close()
   End Sub
End Module
' The example displays the following output:
'    Title:               Country Information
'    nColumns:            5
'    Country:             Country Name         // The localized country name
'    Population:          Population (2010}
'    Area:                Area                 // The area in square miles
'    Capital:             Capital
'    LCity:               Largest City         // The largest city based on 2010 data

Jeśli UseResXDataNodes parametr ma truewartość , ResXDataNode elementy wyliczenia mogą być następujące:

  • Nazwane zasoby wraz z ich danymi. W tym przypadku ResXDataNode.FileRef właściwość to null.

  • Nazwane zasoby wraz z nazwą pliku zawierającego dane zasobów. W takim przypadku ResXDataNode.FileRef właściwość zwraca ResXFileRef obiekt, który zawiera informacje o zasobie, w tym jego nazwę pliku. Jeśli są używane względne nazwy plików, należy zawsze ustawić BasePath właściwość , aby podać punkt odniesienia dla względnej ścieżki pliku.

Jeśli chcesz pobrać nazwane zasoby z pliku resx zamiast wyliczać jego zasoby, możesz utworzyć ResXResourceSet wystąpienie obiektu i wywołać jego GetString metody i GetObject .

Uwaga

Klasa ResXResourceReader zawiera żądanie łącza i żądanie dziedziczenia na poziomie klasy, który ma zastosowanie do wszystkich składowych. Wyjątek SecurityException jest zgłaszany, gdy bezpośredni obiekt wywołujący lub klasa pochodna nie ma uprawnienia pełnego zaufania.

Konstruktory

ResXResourceReader(Stream)

Inicjuje ResXResourceReader nowe wystąpienie klasy dla określonego strumienia.

ResXResourceReader(Stream, AssemblyName[])

Inicjuje ResXResourceReader nowe wystąpienie klasy przy użyciu strumienia i tablicy nazw zestawów.

ResXResourceReader(Stream, ITypeResolutionService)

Inicjuje ResXResourceReader nowe wystąpienie klasy przy użyciu strumienia wejściowego i usługi rozpoznawania typów.

ResXResourceReader(String)

Inicjuje ResXResourceReader nowe wystąpienie klasy dla określonego pliku zasobów.

ResXResourceReader(String, AssemblyName[])

Inicjuje nowe wystąpienie ResXResourceReader klasy przy użyciu nazwy pliku zasobów XML i tablicy nazw zestawów.

ResXResourceReader(String, ITypeResolutionService)

Inicjuje ResXResourceReader nowe wystąpienie klasy przy użyciu nazwy pliku i usługi rozpoznawania typów.

ResXResourceReader(TextReader)

Inicjuje ResXResourceReader nowe wystąpienie klasy dla określonego TextReaderelementu .

ResXResourceReader(TextReader, AssemblyName[])

Inicjuje ResXResourceReader nowe wystąpienie klasy przy użyciu TextReader obiektu i tablicy nazw zestawów.

ResXResourceReader(TextReader, ITypeResolutionService)

Inicjuje ResXResourceReader nowe wystąpienie klasy przy użyciu czytnika strumienia tekstu i usługi rozpoznawania typów.

Właściwości

BasePath

Pobiera lub ustawia ścieżkę podstawową dla względnej ścieżki pliku określonej w ResXFileRef obiekcie.

UseResXDataNodes

Pobiera lub ustawia wartość wskazującą, czy ResXDataNode obiekty są zwracane podczas odczytywania bieżącego pliku zasobu XML, czy strumienia.

Metody

Close()

Zwalnia wszelkie zasoby używane przez element ResXResourceReader.

Dispose(Boolean)

Zwalnia zasoby niezarządzane używane przez element ResXResourceReader i opcjonalnie zwalnia zasoby zarządzane.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
Finalize()

Ten element członkowski zastępuje metodę Finalize() .

FromFileContents(String)

Tworzy nowy ResXResourceReader obiekt i inicjuje go w celu odczytania ciągu, którego zawartość ma postać pliku zasobów XML.

FromFileContents(String, AssemblyName[])

Tworzy nowy ResXResourceReader obiekt i inicjuje go w celu odczytania ciągu, którego zawartość jest w postaci pliku zasobów XML, oraz do rozpoznawania nazw typów określonych w zasobie za pomocą tablicy AssemblyName obiektów.

FromFileContents(String, ITypeResolutionService)

Tworzy nowy ResXResourceReader obiekt i inicjuje go w celu odczytania ciągu, którego zawartość jest w postaci pliku zasobów XML, oraz rozpoznawania nazw typów określonych w zasobie za pomocą ITypeResolutionService obiektu.

GetEnumerator()

Zwraca moduł wyliczający dla bieżącego ResXResourceReader obiektu.

GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetMetadataEnumerator()

Udostępnia moduł wyliczający słownika, który może pobierać właściwości czasu projektowania z bieżącego pliku zasobu XML lub strumienia.

GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

IDisposable.Dispose()

Zwalnia zasoby niezarządzane używane przez element ResXResourceReader i opcjonalnie zwalnia zasoby zarządzane. Aby uzyskać opis tego elementu członkowskiego, zobacz metodę Dispose() .

IEnumerable.GetEnumerator()

Zwraca moduł wyliczający dla bieżącego ResXResourceReader obiektu. Aby uzyskać opis tego elementu członkowskiego, zobacz metodę GetEnumerator() .

Metody rozszerzania

Cast<TResult>(IEnumerable)

Rzutuje elementy obiektu IEnumerable na określony typ.

OfType<TResult>(IEnumerable)

Filtruje elementy IEnumerable elementu na podstawie określonego typu.

AsParallel(IEnumerable)

Umożliwia równoległość zapytania.

AsQueryable(IEnumerable)

Konwertuje element IEnumerable na .IQueryable

Dotyczy

Zobacz też