ResXResourceReader ResXResourceReader ResXResourceReader ResXResourceReader Class

定义

枚举 XML 资源 (.resx) 文件和流,并读取顺序资源名称和值对。Enumerates XML resource (.resx) files and streams, and reads the sequential resource name and value pairs.

public ref class ResXResourceReader : System::Resources::IResourceReader
public class ResXResourceReader : System.Resources.IResourceReader
type ResXResourceReader = class
    interface IResourceReader
    interface IEnumerable
    interface IDisposable
Public Class ResXResourceReader
Implements IResourceReader
继承
ResXResourceReaderResXResourceReaderResXResourceReaderResXResourceReader
实现

示例

下面的示例演示如何使用ResXResourceReader来循环访问 .resx 文件中的资源。The following example demonstrates how to use a ResXResourceReader to iterate through the resources in a .resx file. 首先, ResXResourceReader rsxr为文件items.resx创建。First, the ResXResourceReaderrsxr is created for the file items.resx. 接下来, GetEnumerator使用方法IDictionaryEnumerator创建来循环访问资源, 并将内容显示到控制台。Next, the GetEnumerator method is used to create an IDictionaryEnumerator to iterate through the resources and display the contents to the console.

#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

注解

类提供IResourceReader接口的默认实现, 该接口以 XML 格式读取资源信息。 ResXResourceReaderThe ResXResourceReader class provides a default implementation of the IResourceReader interface that reads resource information in an XML format. 若要从二进制资源格式读取资源信息, 请使用ResourceReader类。To read resource information from a binary resource format, use the ResourceReader class.

通过遍历由ResXResourceReader IDictionaryEnumerator方法返回的字典枚举器(),可以使用类来枚举.resx文件GetEnumerator中的资源。You use the ResXResourceReader class to enumerate resources in .resx files by traversing the dictionary enumerator (IDictionaryEnumerator) that is returned by the GetEnumerator method. 调用提供IDictionaryEnumerator的方法来前进到下一个资源, 并读取 .resx 文件中每个资源的名称和值。You call the methods provided by IDictionaryEnumerator to advance to the next resource and to read the name and value of each resource in the .resx file.

备注

ResXResourceReader类提供两个枚举器。The ResXResourceReader class provides two enumerators. ResXResourceReader.GetEnumerator 方法IDictionaryEnumerator返回对象; 建议使用此方法来枚举资源。The ResXResourceReader.GetEnumerator method returns an IDictionaryEnumerator object; we recommend that you use this method to enumerate resources. 方法是一个显式接口实现, 它IEnumerator返回对象; 我们不建议使用它。 ResXResourceReader.IEnumerable.GetEnumeratorThe ResXResourceReader.IEnumerable.GetEnumerator method is an explicit interface implementation that returns an IEnumerator object; we do not recommend its use.

下面的示例使用GetEnumerator方法来获取一个IDictionaryEnumerator对象, 该对象用于枚举 .resx 文件中的资源。The following example uses the GetEnumerator method to obtain an IDictionaryEnumerator object that is used to enumerate the resources in a .resx file. 该示例包括一个CreateResourceFile用于创建所需的资源文件的例程。The example includes a CreateResourceFile routine that creates the necessary resource file.

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

如果属性为true ResXDataNode , 则属性的值为对象而不是资源值。 IDictionaryEnumerator.Value UseResXDataNodesIf the UseResXDataNodes property is true, the value of the IDictionaryEnumerator.Value property is a ResXDataNode object rather than the resource value. 这会使资源项的注释可用于ResXDataNode.Comment属性。This makes a resource item's comment available from the ResXDataNode.Comment property. 下面的示例将UseResXDataNodes属性设置为true , 并枚举 .resx 文件中的资源。The following example sets the UseResXDataNodes property to true and enumerates the resources in a .resx file,

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

如果UseResXDataNodes ResXDataNodetrue, 则枚举中的项可以是:If UseResXDataNodes is true, the ResXDataNode items in the enumeration can be either:

  • 命名资源及其数据。Named resources along with their data. 在这种情况下ResXDataNode.FileRef , 属性null为。In this case, the ResXDataNode.FileRef property is null.

  • 命名的资源以及包含资源数据的文件的名称。Named resources along with the name of the file that contains the resource data. 在这种情况下ResXDataNode.FileRef , 属性将ResXFileRef返回一个对象, 该对象提供有关资源的信息, 包括其文件名。In this case, the ResXDataNode.FileRef property returns a ResXFileRef object that provides information about the resource, including its filename. 如果使用了相对文件名, 则应始终将BasePath属性设置为提供相对文件路径的参考点。If relative file names are used, you should always set the BasePath property to provide a reference point for the relative file path.

如果要从 .resx 文件中检索命名资源而不是枚举其资源, 可以实例化ResXResourceSet对象并调用其GetStringGetObject方法。If you want to retrieve named resources from a .resx file rather than enumerating its resources, you can instantiate a ResXResourceSet object and call its GetString and GetObject methods.

备注

ResXResourceReader类包含应用于所有成员的类级别的链接要求和继承要求。The ResXResourceReader class contains a link demand and an inheritance demand at the class level that applies to all members. 当直接调用方或派生类不具有完全信任权限时, 将引发异常。SecurityExceptionA SecurityException exception is thrown when either the immediate caller or the derived class does not have full-trust permission.

构造函数

ResXResourceReader(Stream) ResXResourceReader(Stream) ResXResourceReader(Stream) ResXResourceReader(Stream)

为指定的流初始化 ResXResourceReader 类的新实例。Initializes a new instance of the ResXResourceReader class for the specified stream.

ResXResourceReader(Stream, AssemblyName[]) ResXResourceReader(Stream, AssemblyName[]) ResXResourceReader(Stream, AssemblyName[]) ResXResourceReader(Stream, AssemblyName[])

使用流和程序集名称数组初始化 ResXResourceReader 类的新实例。Initializes a new instance of the ResXResourceReader class using a stream and an array of assembly names.

ResXResourceReader(Stream, ITypeResolutionService) ResXResourceReader(Stream, ITypeResolutionService) ResXResourceReader(Stream, ITypeResolutionService) ResXResourceReader(Stream, ITypeResolutionService)

使用输入流和类型解析服务初始化 ResXResourceReader 类的新实例。Initializes a new instance of the ResXResourceReader class using an input stream and a type resolution service.

ResXResourceReader(String) ResXResourceReader(String) ResXResourceReader(String) ResXResourceReader(String)

为指定的资源文件初始化 ResXResourceReader 类的新实例。Initializes a new instance of the ResXResourceReader class for the specified resource file.

ResXResourceReader(String, AssemblyName[]) ResXResourceReader(String, AssemblyName[]) ResXResourceReader(String, AssemblyName[]) ResXResourceReader(String, AssemblyName[])

使用 XML 资源文件名和程序集名称数组初始化 ResXResourceReader 类的新实例。Initializes a new instance of the ResXResourceReader class using an XML resource file name and an array of assembly names.

ResXResourceReader(String, ITypeResolutionService) ResXResourceReader(String, ITypeResolutionService) ResXResourceReader(String, ITypeResolutionService) ResXResourceReader(String, ITypeResolutionService)

使用文件名和类型解析服务初始化 ResXResourceReader 类的新实例。Initializes a new instance of the ResXResourceReader class using a file name and a type resolution service.

ResXResourceReader(TextReader) ResXResourceReader(TextReader) ResXResourceReader(TextReader) ResXResourceReader(TextReader)

为指定的 TextReader 初始化 ResXResourceReader 类的新实例。Initializes a new instance of the ResXResourceReader class for the specified TextReader.

ResXResourceReader(TextReader, AssemblyName[]) ResXResourceReader(TextReader, AssemblyName[]) ResXResourceReader(TextReader, AssemblyName[]) ResXResourceReader(TextReader, AssemblyName[])

使用 ResXResourceReader 对象和程序集名称数组初始化 TextReader 类的新实例。Initializes a new instance of the ResXResourceReader class using a TextReader object and an array of assembly names.

ResXResourceReader(TextReader, ITypeResolutionService) ResXResourceReader(TextReader, ITypeResolutionService) ResXResourceReader(TextReader, ITypeResolutionService) ResXResourceReader(TextReader, ITypeResolutionService)

使用文本流读取器和类型解析服务初始化 ResXResourceReader 类的新实例。Initializes a new instance of the ResXResourceReader class using a text stream reader and a type resolution service.

属性

BasePath BasePath BasePath BasePath

获取或设置在 ResXFileRef 对象中指定的相对文件路径的基路径。Gets or sets the base path for the relative file path specified in a ResXFileRef object.

UseResXDataNodes UseResXDataNodes UseResXDataNodes UseResXDataNodes

获取或设置一个值,该值指示是否在读取当前 XML 资源文件或流时返回 ResXDataNode 对象。Gets or sets a value that indicates whether ResXDataNode objects are returned when reading the current XML resource file or stream.

方法

Close() Close() Close() Close()

释放由 ResXResourceReader 使用的所有资源。Releases all resources used by the ResXResourceReader.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 ResXResourceReader 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the ResXResourceReader and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

此成员重写 Finalize() 方法。This member overrides the Finalize() method.

FromFileContents(String) FromFileContents(String) FromFileContents(String) FromFileContents(String)

创建一个新 ResXResourceReader 对象,然后将它初始化,以读取内容为 XML 资源文件格式的字符串。Creates a new ResXResourceReader object and initializes it to read a string whose contents are in the form of an XML resource file.

FromFileContents(String, AssemblyName[]) FromFileContents(String, AssemblyName[]) FromFileContents(String, AssemblyName[]) FromFileContents(String, AssemblyName[])

创建一个新 ResXResourceReader 对象,然后将它初始化,以读取内容为 XML 资源文件格式的字符串并使用 AssemblyName 对象数组解析资源中指定的类型名称。Creates a new ResXResourceReader object and initializes it to read a string whose contents are in the form of an XML resource file, and to use an array of AssemblyName objects to resolve type names specified in a resource.

FromFileContents(String, ITypeResolutionService) FromFileContents(String, ITypeResolutionService) FromFileContents(String, ITypeResolutionService) FromFileContents(String, ITypeResolutionService)

创建一个新 ResXResourceReader 对象,然后将它初始化,以读取内容为 XML 资源文件格式的字符串并使用 ITypeResolutionService 对象解析资源中指定的类型名称。Creates a new ResXResourceReader object and initializes it to read a string whose contents are in the form of an XML resource file, and to use an ITypeResolutionService object to resolve type names specified in a resource.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

返回当前 ResXResourceReader 对象的一个枚举数。Returns an enumerator for the current ResXResourceReader object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetMetadataEnumerator() GetMetadataEnumerator() GetMetadataEnumerator() GetMetadataEnumerator()

提供一个字典枚举数,该枚举数可以从当前 XML 资源文件或流中检索设计时属性。Provides a dictionary enumerator that can retrieve the design-time properties from the current XML resource file or stream.

GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

释放由 ResXResourceReader 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the ResXResourceReader and optionally releases the managed resources. 有关此成员的说明,请参见 Dispose() 方法。For a description of this member, see the Dispose() method.

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

返回当前 ResXResourceReader 对象的一个枚举数。Returns an enumerator for the current ResXResourceReader object. 有关此成员的说明,请参见 GetEnumerator() 方法。For a description of this member, see the GetEnumerator() method.

扩展方法

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

安全性

LinkDemand
完全信任直接调用方。for full trust for the immediate caller. 此成员不能由部分信任的代码使用。This member cannot be used by partially trusted code.

InheritanceDemand
完全信任继承者。for full trust for inheritors. 此类不能由部分信任的代码继承。This class cannot be inherited by partially trusted code.

适用于

另请参阅