ResourceReader ResourceReader ResourceReader ResourceReader Class

定义

通过读取顺序资源名称/值对枚举二进制资源 (.resources) 文件的资源。Enumerates the resources in a binary resources (.resources) file by reading sequential resource name/value pairs.

public ref class ResourceReader sealed : System::Resources::IResourceReader
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ResourceReader : System.Resources.IResourceReader
type ResourceReader = class
    interface IResourceReader
    interface IEnumerable
    interface IDisposable
Public NotInheritable Class ResourceReader
Implements IResourceReader
继承
ResourceReaderResourceReaderResourceReaderResourceReader
属性
实现

注解

重要

使用不受信任的数据调用此类中的方法存在安全风险。Calling methods from this class with untrusted data is a security risk. 仅使用受信任的数据调用此类中的方法。Call the methods from this class only with trusted data. 有关详细信息,请参阅数据验证For more information, see Data Validation.

类提供IResourceReader接口的标准实现。 ResourceReaderThe ResourceReader class provides a standard implementation of the IResourceReader interface. ResourceReader实例表示嵌入到程序集中的独立 .resources 文件或 .resources 文件。A ResourceReader instance represents either a standalone .resources file or a .resources file that is embedded in an assembly. 它用于枚举 .resources 文件中的资源,并检索其名称/值对。It is used to enumerate the resources in a .resources file and retrieve its name/value pairs. 它与ResourceManager类不同,后者用于从嵌入在程序集中的 .resources 文件中检索指定的已命名资源。It differs from the ResourceManager class, which is used to retrieve specified named resources from a .resources file that is embedded in an assembly. 类用于检索事先知道其名称的资源, ResourceReader而类可用于检索在编译时不知道其数字或精确名称的资源。 ResourceManagerThe ResourceManager class is used to retrieve resources whose names are known in advance, whereas the ResourceReader class is useful for retrieving resources whose number or precise names are not known at compile time. 例如,应用程序可以使用资源文件来存储组织中的部分和项的配置信息,其中节或节中的项的数目事先是未知的。For example, an application may use a resources file to store configuration information that is organized into sections and items in a section, where the number of sections or items in a section is not known in advance. Section1 Section1Item1然后,可以ResourceReader使用对象大致命名资源(例如、 、等)并检索资源。Section1Item2Resources can then be named generically (such as Section1, Section1Item1, Section1Item2, and so on) and retrieved by using a ResourceReader object.

重要

此类型实现 IDisposable 接口。This type implements the IDisposable interface. 在使用完类型后,您应直接或间接释放类型。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接释放类型,请在 try/catch 块中调用其 Dispose 方法。To dispose of the type directly, call its Dispose method in a try/catch block. 若要间接释放类型,请使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 有关详细信息,请参阅 IDisposable 接口主题中的“使用实现 IDisposable 的对象”一节。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

有关使用类的ResourceReader详细信息,请参阅以下部分:For more information about using the ResourceReader class, see the following sections:

实例化 ResourceReader 对象Instantiating a ResourceReader Object

.Resources 文件是一个二进制文件,该文件已通过resgen.exe (资源文件生成器)通过文本文件或 XML .resx 文件进行编译。A .resources file is a binary file that has been compiled from either a text file or an XML .resx file by Resgen.exe (Resource File Generator). ResourceReader对象可以表示独立 .resources 文件或已嵌入到程序集中的 .resources 文件。A ResourceReader object can represent either a standalone .resources file or a .resources file that has been embedded in an assembly.

若要实例ResourceReader化从独立 .resources 文件中读取的对象,请ResourceReader将类构造函数用于输入流或包含 .resources 文件名称的字符串。To instantiate a ResourceReader object that reads from a standalone .resources file, use the ResourceReader class constructor with either an input stream or a string that contains the .resources file name. 下面的示例演示了这两种方法。The following example illustrates both approaches. 第一个实例化ResourceReader一个对象,该对象表示一个名Resources1.resources为的 .resources 文件,使用其文件名。The first instantiates a ResourceReader object that represents a .resources file named Resources1.resources by using its file name. 第二个实例ResourceReader化一个对象,该对象表示使用Resources2.resources从文件创建的流命名的 .resources 文件。The second instantiates a ResourceReader object that represents a .resources file named Resources2.resources by using a stream created from the file.

// Instantiate a standalone .resources file from its filename.
var rr1 = new System.Resources.ResourceReader("Resources1.resources");

// Instantiate a standalone .resources file from a stream.
var fs = new System.IO.FileStream(@".\Resources2.resources",
                                  System.IO.FileMode.Open);
var rr2 = new System.Resources.ResourceReader(fs);      
' Instantiate a standalone .resources file from its filename.
Dim rr1 As New System.Resources.ResourceReader("Resources1.resources")

' Instantiate a standalone .resources file from a stream.
Dim fs As New System.IO.FileStream(".\Resources2.resources",
                                   System.IO.FileMode.Open)
Dim rr2 As New System.Resources.ResourceReader(fs)      

若要创建ResourceReader表示嵌入 .resources 文件的对象,请从嵌入 .resources Assembly文件的程序集中实例化对象。To create a ResourceReader object that represents an embedded .resources file, instantiate an Assembly object from the assembly in which the .resources file is embedded. Assembly.GetManifestResourceStream方法Stream返回可传递给构造ResourceReader(Stream)函数的对象。Its Assembly.GetManifestResourceStream method returns a Stream object that can be passed to the ResourceReader(Stream) constructor. 下面的示例实例化ResourceReader一个表示嵌入 .resources 文件的对象。The following example instantiates a ResourceReader object that represents an embedded .resources file.

System.Reflection.Assembly assem = 
             System.Reflection.Assembly.LoadFrom(@".\MyLibrary.dll"); 
System.IO.Stream fs = 
             assem.GetManifestResourceStream("MyCompany.LibraryResources.resources");
var rr = new System.Resources.ResourceReader(fs); 
Dim assem As System.Reflection.Assembly = 
             System.Reflection.Assembly.LoadFrom(".\MyLibrary.dll") 
Dim fs As System.IO.Stream = 
             assem.GetManifestResourceStream("MyCompany.LibraryResources.resources")
Dim rr As New System.Resources.ResourceReader(fs) 

枚举 ResourceReader 对象的资源Enumerating a ResourceReader Object's Resources

若要枚举 .resources 文件中的资源,请调用GetEnumerator System.Collections.IDictionaryEnumerator返回对象的方法。To enumerate the resources in a .resources file, you call the GetEnumerator method, which returns an System.Collections.IDictionaryEnumerator object. 调用IDictionaryEnumerator.MoveNext方法以从一个资源移到下一个资源。You call the IDictionaryEnumerator.MoveNext method to move from one resource to the next. 如果已枚举false .resources 文件中的所有资源,则方法将返回。The method returns false when all the resources in the .resources file have been enumerated.

备注

IEnumerable.GetEnumerator尽管类实现接口和方法,但方法并不提供实现。IEnumerable.GetEnumerator ResourceReader.GetEnumerator IEnumerable ResourceReaderAlthough the ResourceReader class implements the IEnumerable interface and the IEnumerable.GetEnumerator method, the ResourceReader.GetEnumerator method does not provide the IEnumerable.GetEnumerator implementation. 相反,该ResourceReader.GetEnumerator方法IDictionaryEnumerator返回提供对每个资源的名称/值对的访问的接口对象。Instead, the ResourceReader.GetEnumerator method returns an IDictionaryEnumerator interface object that provides access to each resource's name/value pair.

可以通过两种方式检索集合中的单个资源:You can retrieve the individual resources in the collection in two ways:

使用 IDictionaryEnumerator 属性检索资源Retrieving Resources by Using IDictionaryEnumerator Properties

枚举 .resources 文件中的资源的第一种方法涉及直接检索每个资源的名称/值对。The first method of enumerating the resources in a .resources file involves directly retrieving each resource's name/value pair. 调用IDictionaryEnumerator.MoveNext方法移动到集合中的每个资源后,可以IDictionaryEnumerator.Key从属性和IDictionaryEnumerator.Value属性的资源数据中检索资源名称。After you call the IDictionaryEnumerator.MoveNext method to move to each resource in the collection, you can retrieve the resource name from the IDictionaryEnumerator.Key property and the resource data from the IDictionaryEnumerator.Value property.

下面的示例演示如何使用IDictionaryEnumerator.KeyIDictionaryEnumerator.Value属性检索 .resources 文件中每个资源的名称和值。The following example shows how to retrieve the name and value of each resource in a .resources file by using the IDictionaryEnumerator.Key and IDictionaryEnumerator.Value properties. 若要运行该示例,请创建名为 ApplicationResources 的以下文本文件来定义字符串资源。To run the example, create the following text file named ApplicationResources.txt to define string resources.

Title="Contact Information"  
Label1="First Name:"  
Label2="Middle Name:"  
Label3="Last Name:"  
Label4="SSN:"  
Label5="Street Address:"  
Label6="City:"  
Label7="State:"  
Label8="Zip Code:"  
Label9="Home Phone:"  
Label10="Business Phone:"  
Label11="Mobile Phone:"  
Label12="Other Phone:"  
Label13="Fax:"  
Label14="Email Address:"  
Label15="Alternate Email Address:"  

然后,可以使用以下命令将文本资源文件转换为名为 ApplicationResources 的二进制文件:You can then convert the text resource file to a binary file named ApplicationResources.resources by using the following command:

resgen ApplicationResourcesresgen ApplicationResources.txt

下面的示例使用ResourceReader类来枚举独立的二进制 .resources 文件中的每个资源,并显示其密钥名称和相应的值。The following example then uses the ResourceReader class to enumerate each resource in the standalone binary .resources file and to display its key name and corresponding value.

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

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Resources in ApplicationResources.resources:");
      ResourceReader res = new ResourceReader(@".\ApplicationResources.resources");
      IDictionaryEnumerator dict = res.GetEnumerator();
      while (dict.MoveNext())
         Console.WriteLine("   {0}: '{1}' (Type {2})", 
                           dict.Key, dict.Value, dict.Value.GetType().Name);
      res.Close();
   }
}
// The example displays the following output:
//       Resources in ApplicationResources.resources:
//          Label3: '"Last Name:"' (Type String)
//          Label2: '"Middle Name:"' (Type String)
//          Label1: '"First Name:"' (Type String)
//          Label7: '"State:"' (Type String)
//          Label6: '"City:"' (Type String)
//          Label5: '"Street Address:"' (Type String)
//          Label4: '"SSN:"' (Type String)
//          Label9: '"Home Phone:"' (Type String)
//          Label8: '"Zip Code:"' (Type String)
//          Title: '"Contact Information"' (Type String)
//          Label12: '"Other Phone:"' (Type String)
//          Label13: '"Fax:"' (Type String)
//          Label10: '"Business Phone:"' (Type String)
//          Label11: '"Mobile Phone:"' (Type String)
//          Label14: '"Email Address:"' (Type String)
//          Label15: '"Alternate Email Address:"' (Type String)
Imports System.Collections
Imports System.Resources

Module Example
   Public Sub Main()
      Console.WriteLine("Resources in ApplicationResources.resources:")
      Dim res As New ResourceReader(".\ApplicationResources.resources")
      Dim dict As IDictionaryEnumerator = res.GetEnumerator()
      Do While dict.MoveNext()
         Console.WriteLine("   {0}: '{1}' (Type {2})", dict.Key, dict.Value, dict.Value.GetType().Name)
      Loop
      res.Close()
   End Sub
End Module
' The example displays output like the following:
'       Resources in ApplicationResources.resources:
'          Label3: '"Last Name:"' (Type String)
'          Label2: '"Middle Name:"' (Type String)
'          Label1: '"First Name:"' (Type String)
'          Label7: '"State:"' (Type String)
'          Label6: '"City:"' (Type String)
'          Label5: '"Street Address:"' (Type String)
'          Label4: '"SSN:"' (Type String)
'          Label9: '"Home Phone:"' (Type String)
'          Label8: '"Zip Code:"' (Type String)
'          Title: '"Contact Information"' (Type String)
'          Label12: '"Other Phone:"' (Type String)
'          Label13: '"Fax:"' (Type String)
'          Label10: '"Business Phone:"' (Type String)
'          Label11: '"Mobile Phone:"' (Type String)
'          Label14: '"Email Address:"' (Type String)
'          Label15: '"Alternate Email Address:"' (Type String)

尝试从IDictionaryEnumerator.Value属性中检索资源数据会引发以下异常:The attempt to retrieve resource data from the IDictionaryEnumerator.Value property can throw the following exceptions:

通常,如果在手动修改了某个类型的程序集时已手动修改了该类型的程序集,或该程序集已被无意中删除,或者如果该程序集是较旧的版本,则会引发这些异常。类型。Typically, these exceptions are thrown if the .resources file has been modified manually, if the assembly in which a type is defined has either not been included with an application or has been inadvertently deleted, or if the assembly is an older version that predates a type. 如果引发其中一个异常,可以通过枚举每个资源并调用GetResourceData方法来检索资源,如以下部分所示。If one of these exceptions is thrown, you can retrieve resources by enumerating each resource and calling the GetResourceData method, as the following section shows. 此方法提供了有关IDictionaryEnumerator.Value属性尝试返回的数据类型的一些信息。This approach provides you with some information about the data type that the IDictionaryEnumerator.Value property attempted to return.

使用 GetResourceData 按名称检索资源Retrieving Resources by Name with GetResourceData

在 .resources 文件中枚举资源的第二种方法还涉及通过调用IDictionaryEnumerator.MoveNext方法来浏览文件中的资源。The second approach to enumerating resources in a .resources file also involves navigating through the resources in the file by calling the IDictionaryEnumerator.MoveNext method. 对于每个资源,从IDictionaryEnumerator.Key属性中检索资源的名称,然后将其传递GetResourceData(String, String, Byte[])给方法以检索资源的数据。For each resource, you retrieve the resource's name from the IDictionaryEnumerator.Key property, which is then passed to the GetResourceData(String, String, Byte[]) method to retrieve the resource's data. 这在resourceData参数中作为字节数组返回。This is returned as a byte array in the resourceData argument.

与从IDictionaryEnumerator.KeyIDictionaryEnumerator.Value属性检索资源名称和值相比,此方法更难,因为它返回构成资源值的实际字节。This approach is more awkward than retrieving the resource name and value from the IDictionaryEnumerator.Key and IDictionaryEnumerator.Value properties, because it returns the actual bytes that form the resource value. 但是,如果尝试检索资源时引发异常,则GetResourceData方法可以通过提供有关资源的数据类型的信息来帮助确定异常的源。However, if the attempt to retrieve the resource throws an exception, the GetResourceData method can help identify the source of the exception by supplying information about the resource's data type. 有关指示资源的数据类型的字符串的详细信息,请参阅GetResourceDataFor more information about the string that indicates the resource's data type, see GetResourceData.

下面的示例演示如何使用此方法检索资源并处理引发的任何异常。The following example illustrates how to use this approach to retrieve resources and to handle any exceptions that are thrown. 它以编程方式创建一个二进制 .resources 文件,其中包含四个字符串、一个布尔值、一个整数、一个位图DateTimeTZI和一个自定义对象。It programmatically creates a binary .resources file that contains four strings, one Boolean, one integer, one bitmap, and one custom DateTimeTZI object. 若要运行该示例,请执行以下操作:To run the example, do the following:

  1. 创建一个包含该DateTimeTZI结构的名为 Library 的程序集。Create an assembly named Library.dll that contains the DateTimeTZI structure. 下面是该程序集的源代码。The following is the source code for the assembly.

    using System;
    
    [Serializable] public struct DateTimeTZI
    {
      DateTime Date;
      TimeZoneInfo TimeZone;
       
      public DateTimeTZI(DateTime date, TimeZoneInfo tz)
      {
         this.Date = date;
         this.TimeZone = tz;
      }
    
       public override string ToString()
       {
         return String.Format("{0:dd/MM/yyyy hh:mm:ss tt} {1}", 
                              Date, TimeZone.StandardName);
       }
    }
    
    <Serializable> Public Structure DateTimeTZI
      Dim [Date] As DateTime
      Dim TimeZone As TimeZoneInfo
       
      Public Sub New([date] As DateTime, tz As TimeZoneInfo)
         Me.[Date] = [date]
         Me.TimeZone = tz
      End Sub
      
      Public Overrides Function ToString() As String
         Return String.Format("{0:dd/MM/yyyy hh:mm:ss tt} {1}", 
                              [Date], TimeZone.StandardName)
      End Function
    End Structure
    

    使用以下命令编译中C#的源代码:Compile the source code in C# by using the following command:

    csc /t:library library.cs  
    

    或者,可以使用以下命令在 Visual Basic 中对其进行编译:Or, you can compile it in Visual Basic by using the following command:

    vbc library.vb /t:library  
    
  2. 编译并执行以下源代码,这会创建一个名为 ContactResources 的 .resources 文件。Compile and execute the following source code, which creates a .resources file named ContactResources.resources.

    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Resources;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;
    
    
    public class Example
    {
       public static void Main()
       {
          // Bitmap as stream.
          MemoryStream bitmapStream = new MemoryStream();
          Bitmap bmp = new Bitmap(@".\ContactsIcon.jpg");
          bmp.Save(bitmapStream, ImageFormat.Jpeg);
              
          // Define resources to be written.
          using (ResourceWriter rw = new ResourceWriter(@".\ContactResources.resources"))
          {
             rw.AddResource("Title", "Contact List");
             rw.AddResource("NColumns", 5);         
             rw.AddResource("Icon", bitmapStream);         
             rw.AddResource("Header1", "Name");
             rw.AddResource("Header2", "City");
             rw.AddResource("Header3", "State");  
             rw.AddResource("VersionDate", new DateTimeTZI(
                            new DateTime(2012, 5, 18),  
                            TimeZoneInfo.Local));
             rw.AddResource("ClientVersion", true);
             rw.Generate();
          }
       }
    }
    
    Imports System.Drawing
    Imports System.IO
    Imports System.Resources
    Imports System.Runtime.Serialization.Formatters.Binary
    
    Imports System.Text
    
    Module Example
       Public Sub Main()
          ' Bitmap as stream.
          Dim bitmapStream As New MemoryStream()
          Dim bmp As New Bitmap(".\ContactsIcon.jpg")
          bmp.Save(bitmapStream, Imaging.ImageFormat.jpeg)
              
          ' Define resources to be written.
          Using rw As New ResourceWriter(".\ContactResources.resources")
             rw.AddResource("Title", "Contact List")
             rw.AddResource("NColumns", 5)         
             rw.AddResource("Icon", bitmapStream)         
             rw.AddResource("Header1", "Name")
             rw.AddResource("Header2", "City")
             rw.AddResource("Header3", "State")  
             rw.AddResource("VersionDate", New DateTimeTZI(#05/18/2012#, 
                                                           TimeZoneInfo.Local))
             rw.AddResource("ClientVersion", True)
             rw.Generate()
          End Using
       End Sub
    End Module
    

    源代码文件被命名为 CreateResources.cs。The source code file is named CreateResources.cs. 可以使用以下命令在C#中对其进行编译:You can compile it in C# by using the following command:

    csc CreateResources.cs /r:library.dll  
    

    或者,可以使用以下命令在 Visual Basic 中对其进行编译:Or, you can compile it in Visual Basic by using the following command:

    vbc CreateResources.vb /r:library.dll  
    
  3. 编译并运行以下代码以枚举 ContactResources 文件中的资源。Compile and run the following code to enumerate the resources in the ContactResources.resources file.

    using System;
    using System.Collections;
    using System.Drawing;
    using System.IO;
    using System.Resources;
    using System.Runtime.Serialization.Formatters.Binary;
    
    public class Example
    {
       public static void Main()
       {
          ResourceReader rdr = new ResourceReader(@".\ContactResources.resources");  
          IDictionaryEnumerator dict = rdr.GetEnumerator();
          while (dict.MoveNext()) {
             Console.WriteLine("Resource Name: {0}", dict.Key);
             try {
                Console.WriteLine("   Value: {0}", dict.Value);
             }
             catch (FileNotFoundException) {
                Console.WriteLine("   Exception: A file cannot be found.");
                DisplayResourceInfo(rdr, (string) dict.Key, false);
             }
             catch (FormatException) {
                Console.WriteLine("   Exception: Corrupted data.");
                DisplayResourceInfo(rdr, (string) dict.Key, true);
             }
             catch (TypeLoadException) {
                Console.WriteLine("   Exception: Cannot load the data type.");
                DisplayResourceInfo(rdr, (string) dict.Key, false);   
             }
          } 
       }
    
       private static void DisplayResourceInfo(ResourceReader rr, 
                                       string key, bool loaded)
       {                                
          string dataType = null;
          byte[] data = null;
          rr.GetResourceData(key, out dataType, out data);
                
          // Display the data type.
          Console.WriteLine("   Data Type: {0}", dataType);
          // Display the bytes that form the available data.      
          Console.Write("   Data: ");
          int lines = 0;
          foreach (var dataItem in data) {
             lines++;
             Console.Write("{0:X2} ", dataItem);
             if (lines % 25 == 0)
                Console.Write("\n         ");
          }
          Console.WriteLine();
          // Try to recreate current state of  data.
          // Do: Bitmap, DateTimeTZI
          switch (dataType) 
          {  
             // Handle internally serialized string data (ResourceTypeCode members).
             case "ResourceTypeCode.String":
                BinaryReader reader = new BinaryReader(new MemoryStream(data));
                string binData = reader.ReadString();
                Console.WriteLine("   Recreated Value: {0}", binData);
                break;
             case "ResourceTypeCode.Int32":
                Console.WriteLine("   Recreated Value: {0}", 
                                  BitConverter.ToInt32(data, 0));
                break;
             case "ResourceTypeCode.Boolean":
                Console.WriteLine("   Recreated Value: {0}", 
                                  BitConverter.ToBoolean(data, 0));
                break;
             // .jpeg image stored as a stream.
             case "ResourceTypeCode.Stream":  
                const int OFFSET = 4;
                int size = BitConverter.ToInt32(data, 0);
                Bitmap value1 = new Bitmap(new MemoryStream(data, OFFSET, size));
                Console.WriteLine("   Recreated Value: {0}", value1); 
                break;
             // Our only other type is DateTimeTZI.
             default:
                // No point in deserializing data if the type is unavailable.
                if (dataType.Contains("DateTimeTZI") && loaded) { 
                   BinaryFormatter binFmt = new BinaryFormatter();
                   object value2 = binFmt.Deserialize(new MemoryStream(data));
                   Console.WriteLine("   Recreated Value: {0}", value2);
                }    
                break;
          }
          Console.WriteLine();
       }
    }
    
    Imports System.Collections
    Imports System.Drawing
    Imports System.IO
    Imports System.Resources
    Imports System.Runtime.Serialization.Formatters.Binary
    
    Module Example
       Public Sub Main()
          Dim rdr As New ResourceReader(".\ContactResources.resources")  
          Dim dict As IDictionaryEnumerator = rdr.GetEnumerator()
          Do While dict.MoveNext()
             Console.WriteLine("Resource Name: {0}", dict.Key)
             Try
                Console.WriteLine("   Value: {0}", dict.Value)
             Catch e As FileNotFoundException
                Console.WriteLine("   Exception: A file cannot be found.")
                DisplayResourceInfo(rdr, CStr(dict.Key), False)
             Catch e As FormatException
                Console.WriteLine("   Exception: Corrupted data.")
                DisplayResourceInfo(rdr, CStr(dict.Key), True)
             Catch e As TypeLoadException
                Console.WriteLine("   Exception: Cannot load the data type.")
                DisplayResourceInfo(rdr, CStr(dict.Key), False)   
             End Try
          Loop 
       End Sub
    
       Private Sub DisplayResourceInfo(rr As ResourceReader, 
                                       key As String, loaded As Boolean)
          Dim dataType As String = Nothing
          Dim data() As Byte = Nothing
          rr.GetResourceData(key, dataType, data)
                
          ' Display the data type.
          Console.WriteLine("   Data Type: {0}", dataType)
          ' Display the bytes that form the available data.      
          Console.Write("   Data: ")
          Dim lines As Integer = 0
          For Each dataItem In data
             lines += 1
             Console.Write("{0:X2} ", dataItem)
             If lines Mod 25 = 0 Then Console.Write("{0}         ", vbCrLf)
          Next
          Console.WriteLine()
          ' Try to recreate current state of  data.
          ' Do: Bitmap, DateTimeTZI
          Select Case dataType   
             ' Handle internally serialized string data (ResourceTypeCode members).
             Case "ResourceTypeCode.String"
                Dim reader As New BinaryReader(New MemoryStream(data))
                Dim binData As String = reader.ReadString()
                Console.WriteLine("   Recreated Value: {0}", binData)
             Case "ResourceTypeCode.Int32"
                Console.WriteLine("   Recreated Value: {0}", 
                                  BitConverter.ToInt32(data, 0))
             Case "ResourceTypeCode.Boolean"
                Console.WriteLine("   Recreated Value: {0}", 
                                  BitConverter.ToBoolean(data, 0))
             ' .jpeg image stored as a stream.
             Case "ResourceTypeCode.Stream"  
                Const OFFSET As Integer = 4
                Dim size As Integer = BitConverter.ToInt32(data, 0)
                Dim value As New Bitmap(New MemoryStream(data, OFFSET, size))
                Console.WriteLine("   Recreated Value: {0}", value) 
             ' Our only other type is DateTimeTZI.
             Case Else
                ' No point in deserializing data if the type is unavailable.
                If dataType.Contains("DateTimeTZI") And loaded Then 
                   Dim binFmt As New BinaryFormatter()
                   Dim value As Object = binFmt.Deserialize(New MemoryStream(data))
                   Console.WriteLine("   Recreated Value: {0}", value)
                End If    
          End Select
          Console.WriteLine()
       End Sub
    End Module
    

    修改源代码(例如,通过FormatExceptiontry块末尾特意引发,或重命名库 .dll 程序集,使其在运行时不可用),可以运行该示例, GetResourceData以了解如何调用使您能够检索或重新创建某些资源信息。After modifying the source code (for example, by deliberately throwing a FormatException at the end of the try block) or renaming the Library.dll assembly so that it is unavailable at runtime, you can run the example to see how calls to GetResourceData enable you to retrieve or recreate some resource information.

构造函数

ResourceReader(Stream) ResourceReader(Stream) ResourceReader(Stream) ResourceReader(Stream)

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

ResourceReader(String) ResourceReader(String) ResourceReader(String) ResourceReader(String)

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

方法

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

释放与此 ResourceReader 对象相关联的所有操作系统资源。Releases all operating system resources associated with this ResourceReader object.

Dispose() Dispose() Dispose() Dispose()

释放 ResourceReader 类的当前实例所使用的所有资源。Releases all resources used by the current instance of the ResourceReader class.

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

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

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

返回此 ResourceReader 对象的枚举器。Returns an enumerator for this ResourceReader object.

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

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

(Inherited from Object)
GetResourceData(String, String, Byte[]) GetResourceData(String, String, Byte[]) GetResourceData(String, String, Byte[]) GetResourceData(String, String, Byte[])

从打开的资源文件或流检索指定资源的类型名称和数据。Retrieves the type name and data of a named resource from an open 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()

释放由 ResourceReader 占用的资源。Releases the resources used by the ResourceReader.

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

返回此 ResourceReader 对象的枚举器。Returns an enumerator for this ResourceReader object.

扩展方法

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.

适用于