ResourceReader Sınıf

Tanım

Sıralı kaynak adı/değer çiftlerini okuyarak bir ikili kaynak (. resources) dosyasındaki kaynakları numaralandırır.Enumerates the resources in a binary resources (.resources) file by reading sequential resource name/value pairs.

public ref class ResourceReader sealed : System::Resources::IResourceReader
public ref class ResourceReader sealed : IDisposable
public ref class ResourceReader sealed : IDisposable, System::Collections::IEnumerable, System::Resources::IResourceReader
public sealed class ResourceReader : System.Resources.IResourceReader
public sealed class ResourceReader : IDisposable
public sealed class ResourceReader : IDisposable, System.Collections.IEnumerable, System.Resources.IResourceReader
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ResourceReader : System.Resources.IResourceReader
type ResourceReader = class
    interface IEnumerable
    interface IDisposable
    interface IResourceReader
type ResourceReader = class
    interface IDisposable
type ResourceReader = class
    interface IResourceReader
    interface IEnumerable
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type ResourceReader = class
    interface IResourceReader
    interface IEnumerable
    interface IDisposable
Public NotInheritable Class ResourceReader
Implements IResourceReader
Public NotInheritable Class ResourceReader
Implements IDisposable
Public NotInheritable Class ResourceReader
Implements IDisposable, IEnumerable, IResourceReader
Devralma
ResourceReader
Öznitelikler
Uygulamalar

Açıklamalar

Önemli

Güvenilmeyen verilerle bu sınıftan Yöntemler çağırma bir güvenlik riskidir.Calling methods from this class with untrusted data is a security risk. Bu sınıftan yalnızca güvenilir verilerle Yöntemleri çağırın.Call the methods from this class only with trusted data. Daha fazla bilgi için bkz. veri doğrulama.For more information, see Data Validation.

ResourceReaderSınıfı, arabirimin standart bir uygulamasını sağlar IResourceReader .The ResourceReader class provides a standard implementation of the IResourceReader interface. ResourceReaderÖrnek, bir derlemeye katıştırılmış tek başına. resources dosyasını veya. resources dosyasını temsil eder.A ResourceReader instance represents either a standalone .resources file or a .resources file that is embedded in an assembly. Bir. resources dosyasındaki kaynakları numaralandırmak ve ad/değer çiftlerini almak için kullanılır.It is used to enumerate the resources in a .resources file and retrieve its name/value pairs. ResourceManagerBir derlemeye gömülü bir. resources dosyasından belirtilen adlandırılmış kaynakları almak için kullanılan sınıfından farklılık gösterir.It differs from the ResourceManager class, which is used to retrieve specified named resources from a .resources file that is embedded in an assembly. ResourceManagerSınıfı, adları önceden bilinen kaynakları almak için kullanılır, ancak ResourceReader sınıf numarası veya kesin adları derleme zamanında bilinmeyen kaynakları almak için yararlıdır.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. Örneğin, bir uygulama bir bölümdeki bölümler ve öğeler halinde düzenlenmiş yapılandırma bilgilerini depolamak için bir kaynak dosyası kullanabilir, burada bölüm veya bölümdeki öğe sayısı önceden bilinmiyor.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. Kaynaklar daha sonra genel olarak (örneğin,, vb Section1 Section1Item1 Section1Item2 .) adlandırılabilir ve bir nesnesi kullanılarak alınabilir ResourceReader .Resources can then be named generically (such as Section1, Section1Item1, Section1Item2, and so on) and retrieved by using a ResourceReader object.

Önemli

Bu tür, IDisposable arabirimini uygular.This type implements the IDisposable interface. Türü kullanmayı bitirdiğinizde, bunu doğrudan veya dolaylı olarak atabilirsiniz.When you have finished using the type, you should dispose of it either directly or indirectly. Türü doğrudan atmak için, Dispose yöntemini bir try / catch blokta çağırın.To dispose of the type directly, call its Dispose method in a try/catch block. Dolaylı olarak atmak için using (C# dilinde) veya (Visual Basic) gibi bir dil yapısı kullanın Using .To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Daha fazla bilgi için, interface konusunun "IDisposable uygulayan bir nesne kullanma" bölümüne bakın IDisposable .For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Sınıfını kullanma hakkında daha fazla bilgi için ResourceReader aşağıdaki bölümlere bakın:For more information about using the ResourceReader class, see the following sections:

Bir ResourceReader Nesnesini ÖrneklemeInstantiating a ResourceReader Object

. Resources dosyası, bir metin dosyasından veya bir XML. resx dosyasından Resgen.exe (kaynak dosya Oluşturucu)tarafından derlenen bir ikili dosyadır.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). Bir ResourceReader nesne, bir derlemeye katıştırılmış tek başına. resources dosyasını veya. resources dosyasını temsil edebilir.A ResourceReader object can represent either a standalone .resources file or a .resources file that has been embedded in an assembly.

ResourceReaderTek başına. resources dosyasından okuyan bir nesnenin örneğini oluşturmak için, ResourceReader sınıf oluşturucusunu bir giriş akışı veya. resources dosya adını içeren bir dize ile birlikte kullanın.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. Aşağıdaki örnekte her iki yaklaşım da gösterilmektedir.The following example illustrates both approaches. İlki, ResourceReader dosya adı kullanılarak adlı bir. resources dosyasını temsil eden bir nesnesi başlatır Resources1.resources .The first instantiates a ResourceReader object that represents a .resources file named Resources1.resources by using its file name. İkincisi, ResourceReader Resources2.resources dosyadan oluşturulan bir akış kullanılarak adlı. resources dosyasını temsil eden bir nesne oluşturur.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)      

ResourceReaderGömülü bir. resources dosyasını temsil eden bir nesne oluşturmak için, Assembly . resources dosyasının gömülü olduğu derlemeden bir nesne örneği oluşturun.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.GetManifestResourceStreamYöntemi Stream , oluşturucuya geçirilebilecek bir nesne döndürür ResourceReader(Stream) .Its Assembly.GetManifestResourceStream method returns a Stream object that can be passed to the ResourceReader(Stream) constructor. Aşağıdaki örnek, gömülü bir ResourceReader . resources dosyasını temsil eden bir nesne oluşturur.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) 

Bir ResourceReader Nesnenin Kaynaklarını NumaralandırmaEnumerating a ResourceReader Object's Resources

Bir. resources dosyasındaki kaynakları numaralandırmak için, GetEnumerator bir nesnesi döndüren yöntemini çağırın System.Collections.IDictionaryEnumerator .To enumerate the resources in a .resources file, you call the GetEnumerator method, which returns an System.Collections.IDictionaryEnumerator object. IDictionaryEnumerator.MoveNextBir kaynaktan sonrakine geçmek için yöntemini çağırabilirsiniz.You call the IDictionaryEnumerator.MoveNext method to move from one resource to the next. Yöntemi, false . resources dosyasındaki tüm kaynaklar numaralandırıldıktan sonra döndürülür.The method returns false when all the resources in the .resources file have been enumerated.

Not

ResourceReaderSınıfı IEnumerable arabirimini ve yöntemini uyguluyor olsa da IEnumerable.GetEnumerator , ResourceReader.GetEnumerator Yöntem IEnumerable.GetEnumerator uygulamayı sağlamaz.Although the ResourceReader class implements the IEnumerable interface and the IEnumerable.GetEnumerator method, the ResourceReader.GetEnumerator method does not provide the IEnumerable.GetEnumerator implementation. Bunun yerine, ResourceReader.GetEnumerator yöntemi her bir IDictionaryEnumerator kaynağın ad/değer çiftine erişim sağlayan bir arabirim nesnesi döndürür.Instead, the ResourceReader.GetEnumerator method returns an IDictionaryEnumerator interface object that provides access to each resource's name/value pair.

Koleksiyondaki tek tek kaynakları iki şekilde alabilirsiniz:You can retrieve the individual resources in the collection in two ways:

IDictionaryEnumerator Özelliklerini Kullanarak Kaynakları AlmaRetrieving Resources by Using IDictionaryEnumerator Properties

Bir. resources dosyasındaki kaynakları numaralandırmak için ilk yöntem, her bir kaynağın ad/değer çiftini doğrudan almayı içerir.The first method of enumerating the resources in a .resources file involves directly retrieving each resource's name/value pair. IDictionaryEnumerator.MoveNextKoleksiyondaki her kaynağa geçiş yapmak için yöntemini çağırdığınızda, özelliğinden ve kaynak verilerinden kaynak adı elde edebilirsiniz 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.

Aşağıdaki örnek, ve özelliklerini kullanarak bir. resources dosyasındaki her bir kaynağın adının ve değerinin nasıl alınacağını gösterir IDictionaryEnumerator.Key IDictionaryEnumerator.Value .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. Örneği çalıştırmak için, dize kaynaklarını tanımlamak üzere ApplicationResources.txt adlı aşağıdaki metin dosyasını oluşturun.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:"  

Daha sonra, aşağıdaki komutu kullanarak metin kaynak dosyasını ApplicationResources. resources adlı bir ikili dosyaya dönüştürebilirsiniz: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

Aşağıdaki örnek, ResourceReader tek başına ikili. resources dosyasındaki her bir kaynağı numaralandırmak ve anahtar adını ve karşılık gelen değeri göstermek için sınıfını kullanır.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)

Özelliğinden kaynak verilerini alma girişimi IDictionaryEnumerator.Value aşağıdaki özel durumları oluşturabilir:The attempt to retrieve resource data from the IDictionaryEnumerator.Value property can throw the following exceptions:

Genellikle, bu özel durumlar,. resources dosyası el ile değiştirilmişse, bir türün tanımlandığı derleme bir uygulamayla birlikte içerilmemişse ya da yanlışlıkla silinmişse veya derleme bir tür ön tarihe göre daha eski bir sürümse, bu istisnalar atılır.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. Bu özel durumlardan biri oluşturulursa, GetResourceData aşağıdaki bölümde gösterildiği gibi, her bir kaynağı silerek ve yöntemini çağırarak kaynakları alabilirsiniz.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. Bu yaklaşım, özelliğin dönmesini denediği veri türü hakkında bazı bilgiler sağlar IDictionaryEnumerator.Value .This approach provides you with some information about the data type that the IDictionaryEnumerator.Value property attempted to return.

GetResourceData Yöntemiyle Ada Göre Kaynak AlmaRetrieving Resources by Name with GetResourceData

Bir. resources dosyasındaki kaynakları listelemek için ikinci yaklaşım, yöntemi çağırarak dosyadaki kaynaklar arasında gezinmeyi de kapsar 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. Her kaynak için, kaynağın adını IDictionaryEnumerator.Key özelliğinden alır, bu, daha sonra GetResourceData(String, String, Byte[]) kaynağın verilerini almak için yöntemine geçirilir.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. Bu, bağımsız değişkende bir bayt dizisi olarak döndürülür resourceData .This is returned as a byte array in the resourceData argument.

Bu yaklaşım, kaynak IDictionaryEnumerator.Key IDictionaryEnumerator.Value değerini oluşturan gerçek baytları döndürdüğünden, kaynak adı ve değerin ve özelliklerden alınması daha fazla olabilir.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. Ancak, kaynağı alma girişimi bir özel durum oluşturursa, bu GetResourceData Yöntem, kaynağın veri türü hakkında bilgi sağlayarak özel durumun kaynağını belirlemesine yardımcı olabilir.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. Kaynağın veri türünü gösteren dize hakkında daha fazla bilgi için bkz GetResourceData ..For more information about the string that indicates the resource's data type, see GetResourceData.

Aşağıdaki örnek, bu yaklaşımın kaynakları almak ve oluşturulan özel durumları işlemek için nasıl kullanılacağını gösterir.The following example illustrates how to use this approach to retrieve resources and to handle any exceptions that are thrown. Program aracılığıyla dört dize, bir Boolean, bir tamsayı, bir bit eşlem ve bir özel nesne içeren bir ikili. resources dosyası oluşturur DateTimeTZI .It programmatically creates a binary .resources file that contains four strings, one Boolean, one integer, one bitmap, and one custom DateTimeTZI object. Örneği çalıştırmak için şunları yapın:To run the example, do the following:

  1. Yapıyı içeren Library.dll adlı bir bütünleştirilmiş kod oluşturun DateTimeTZI .Create an assembly named Library.dll that contains the DateTimeTZI structure. Derleme için kaynak kodu aşağıda verilmiştir.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
    

    Aşağıdaki komutu kullanarak C# dilinde kaynak kodu derleyin:Compile the source code in C# by using the following command:

    csc /t:library library.cs  
    

    Veya, aşağıdaki komutu kullanarak Visual Basic derleyebilirsiniz:Or, you can compile it in Visual Basic by using the following command:

    vbc library.vb /t:library  
    
  2. ContactResources. resources adlı bir. resources dosyası oluşturan aşağıdaki kaynak kodu derleyin ve yürütün.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
    

    Kaynak kodu dosyası Createresotut. cs olarak adlandırılır.The source code file is named CreateResources.cs. Aşağıdaki komutu kullanarak C# dilinde derleyebilirsiniz:You can compile it in C# by using the following command:

    csc CreateResources.cs /r:library.dll  
    

    Veya, aşağıdaki komutu kullanarak Visual Basic derleyebilirsiniz:Or, you can compile it in Visual Basic by using the following command:

    vbc CreateResources.vb /r:library.dll  
    
  3. ContactResources. resources dosyasındaki kaynakları numaralandırmak için aşağıdaki kodu derleyin ve çalıştırın.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
    

    Kaynak kodu değiştirdikten sonra (örneğin, FormatException bloğun sonunda bir oluşturarak try ) veya Library.dll derlemesini çalışma zamanında kullanılamaz hale getirmek üzere yeniden adlandırdıktan sonra, GetResourceData bazı kaynak bilgilerini almanızı veya yeniden oluşturmayı sağlayan çağrıların nasıl yapılacağını görmek için örneği çalıştırabilirsiniz.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.

Oluşturucular

ResourceReader(Stream)

ResourceReaderBelirtilen akış için sınıfın yeni bir örneğini başlatır.Initializes a new instance of the ResourceReader class for the specified stream.

ResourceReader(String)

ResourceReaderBelirtilen adlandırılmış kaynak dosyası için sınıfın yeni bir örneğini başlatır.Initializes a new instance of the ResourceReader class for the specified named resource file.

Yöntemler

Close()

Bu nesneyle ilişkili tüm işletim sistemi kaynaklarını serbest bırakır ResourceReader .Releases all operating system resources associated with this ResourceReader object.

Dispose()

ResourceReader sınıfının geçerli örneği tarafından kullanılan tüm kaynakları serbest bırakır.Releases all resources used by the current instance of the ResourceReader class.

Equals(Object)

Belirtilen nesnenin geçerli nesneye eşit olup olmadığını belirler.Determines whether the specified object is equal to the current object.

(Devralındığı yer: Object)
GetEnumerator()

Bu nesne için bir Numaralandırıcı döndürür ResourceReader .Returns an enumerator for this ResourceReader object.

GetHashCode()

Varsayılan karma işlevi olarak işlev görür.Serves as the default hash function.

(Devralındığı yer: Object)
GetResourceData(String, String, Byte[])

Açık kaynak dosyasından veya akıştan adlandırılmış bir kaynağın tür adını ve verilerini alır.Retrieves the type name and data of a named resource from an open resource file or stream.

GetType()

TypeGeçerli örneği alır.Gets the Type of the current instance.

(Devralındığı yer: Object)
MemberwiseClone()

Geçerli bir basit kopyasını oluşturur Object .Creates a shallow copy of the current Object.

(Devralındığı yer: Object)
ToString()

Geçerli nesneyi temsil eden dizeyi döndürür.Returns a string that represents the current object.

(Devralındığı yer: Object)

Belirtik Arabirim Kullanımları

IDisposable.Dispose()

Tarafından kullanılan kaynakları serbest bırakır ResourceReader .Releases the resources used by the ResourceReader.

IEnumerable.GetEnumerator()

Bu nesne için bir Numaralandırıcı döndürür ResourceReader .Returns an enumerator for this ResourceReader object.

Uzantı Metotları

Cast<TResult>(IEnumerable)

Öğesinin öğelerini IEnumerable belirtilen türe yayınlar.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Öğesinin öğelerini IEnumerable belirtilen bir türe göre filtreler.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Bir sorgunun paralelleştirilmesini mümkün hale getirme.Enables parallelization of a query.

AsQueryable(IEnumerable)

Bir IEnumerable öğesine dönüştürür IQueryable .Converts an IEnumerable to an IQueryable.

Şunlara uygulanır