ResourceReader 類別

定義

讀取循序資源名稱/值組,以列舉二進位資源 (.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
繼承
ResourceReader
屬性
實作

備註

重要

使用不信任的資料呼叫此類別的方法,會造成安全性上的風險。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.

ResourceReader 類別提供 IResourceReader 介面的標準執行。The 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. ResourceManager 類別是用來抓取預先知道名稱的資源,而 ResourceReader 類別則可以用來抓取在編譯時期不知道其數目或精確名稱的資源。The 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. 然後可以使用 ResourceReader 物件,以一般方式(例如 Section1Section1Item1Section1Item2等等)來命名資源。Resources 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. 若要直接處置型別,請呼叫其 Disposetry/ 區塊中的 catch 方法。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.

若要具現化從獨立 .resources 檔案讀取的 ResourceReader 物件,請使用 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. 第二個會使用從檔案建立的資料流程,具現化代表名為 Resources2.resources 之 .resources 檔案的 ResourceReader 物件。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)      

若要建立代表內嵌 .resources 檔案的 ResourceReader 物件,請從內嵌 .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 方法會傳回可傳遞至 ResourceReader(Stream) 的函式的 Stream 物件。Its Assembly.GetManifestResourceStream method returns a Stream object that can be passed to the ResourceReader(Stream) constructor. 下列範例會具現化代表內嵌 .resources 檔案的 ResourceReader 物件。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. 當 .resources 檔案中的所有資源都已列舉時,此方法會傳回 falseThe method returns false when all the resources in the .resources file have been enumerated.

注意

雖然 ResourceReader 類別會執行 IEnumerable 介面和 IEnumerable.GetEnumerator 方法,但 ResourceReader.GetEnumerator 方法不會提供 IEnumerable.GetEnumerator 執行。Although 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 ApplicationResources .txtresgen 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:

一般而言,如果已手動修改 .resources 檔案,且已定義類型的元件未包含在應用程式中,或不小心刪除,或元件是比較舊的較舊版本,則會擲回這些例外狀況。型別。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.Key 中抓取資源名稱和值,以及 IDictionaryEnumerator.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. 它會以程式設計方式建立包含四個字串、一個布林值、一個整數、一個點陣圖和一個自訂 DateTimeTZI 物件的二進位 .resources 檔案。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. 建立名為 Library .dll 的元件,其中包含 DateTimeTZI 結構。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 .resources 檔案中的資源。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
    

    修改原始程式碼後(例如,故意在 try 區塊的結尾擲回 FormatException),或重新命名程式庫 .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 類別的新執行個體。Initializes a new instance of the ResourceReader class for the specified stream.

ResourceReader(String)

為指定的具名資源檔初始化 ResourceReader 類別的新執行個體。Initializes a new instance of the ResourceReader class for the specified named resource file.

方法

Close()

將與這個 ResourceReader 物件相關聯的所有作業系統資源釋出。Releases all operating system resources associated with this ResourceReader object.

Dispose()

釋放 ResourceReader 類別目前的執行個體所使用的全部資源。Releases all resources used by the current instance of the ResourceReader class.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetEnumerator()

傳回這個 ResourceReader 物件的列舉值。Returns an enumerator for this ResourceReader object.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetResourceData(String, String, Byte[])

從開啟的資源檔或資料流,擷取具名資源的類型名稱和資料。Retrieves the type name and data of a named resource from an open resource file or stream.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

IDisposable.Dispose()

釋放 ResourceReader 使用的資源。Releases the resources used by the ResourceReader.

IEnumerable.GetEnumerator()

傳回這個 ResourceReader 物件的列舉值。Returns an enumerator for this ResourceReader object.

擴充方法

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

適用於