Csharp/C Sharp/Development Class/Resource ResX — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 11:43, 26 мая 2010

Compile resource into the final exe file

//csc /res:StringTable.resources Test.cs

//File: Test.cs
using System;
using System.Windows.Forms;
using System.Resources;
using System.Reflection;
public class Test
{
   
    public static void Main(String[] a)
    {
        ResourceManager FormResources = new ResourceManager("StringTable", Assembly.GetExecutingAssembly());
        string          Message;
        
        Message = FormResources.GetString("Message");
        MessageBox.Show(Message);
    }
}
//resgen StringTable.txt

/* File:StringTable.txt
#=============
# String Table
#=============
Message = The button has been clicked.
*/


Create File Based Resource Manager

using System;
using System.Globalization;
using System.Resources;
using System.Collections;
class Class1 {
  static void Main(string[] args) {
      ResourceWriter resourceWriter = new ResourceWriter("nfex.resources");
      resourceWriter.AddResource("key 1", "First value");
      resourceWriter.AddResource("key 2", "Second value");
      resourceWriter.AddResource("key 3", "Third value");
      resourceWriter.Generate();
      resourceWriter.Close();
      //Loose resource example
      ResourceManager rm;
      rm = ResourceManager.CreateFileBasedResourceManager("nfex",".",null);
      Console.WriteLine(rm.GetString("key 1"));

   }
}


Create resource file and read value from it

using System;
using System.Globalization;
using System.Resources;
using System.Collections;
class Class1 {
  static void Main(string[] args) {
      ResourceWriter resourceWriter = new ResourceWriter("nfex.resources");
      resourceWriter.AddResource("key 1", "First value");
      resourceWriter.AddResource("key 2", "Second value");
      resourceWriter.AddResource("key 3", "Third value");
      resourceWriter.Generate();
      resourceWriter.Close();
      ResourceSet Rs = new ResourceSet("nfex.resources");
      Console.WriteLine(Rs.GetString("key 1 ", true));
      Console.WriteLine(Rs.GetString("key 2", true));
      Console.WriteLine(Rs.GetString("key 3", true));
      Console.WriteLine(Rs.GetDefaultReader().ToString());
      Rs.Close();
   }
}


Create resource file and read value from it using IDictionaryEnumerator

using System;
using System.Globalization;
using System.Resources;
using System.Collections;
class Class1 {
  static void Main(string[] args) {
      ResourceWriter resourceWriter = new ResourceWriter("nfex.resources");
      resourceWriter.AddResource("key 1", "First value");
      resourceWriter.AddResource("key 2", "Second value");
      resourceWriter.AddResource("key 3", "Third value");
      resourceWriter.Generate();
      resourceWriter.Close();
      ResourceReader resourceReader = new ResourceReader("nfex.resources");
      IDictionaryEnumerator resourceReaderEn = resourceReader.GetEnumerator();
      while (resourceReaderEn.MoveNext())
      {
         Console.WriteLine("Name: {0} - Value: {1}", 
            resourceReaderEn.Key.ToString().PadRight(10, " "), 
            resourceReaderEn.Value);
      }
      resourceReader.Close();
   }
}


Creating a new resource reader

using System;
using System.Resources;
using System.Collections;
public class MyResourceReader : IResourceReader, IEnumerable {
  private Hashtable dict;
  private string fResName;
  void IResourceReader.Close() {
  }
  public void Dispose(){
    
  }
  IDictionaryEnumerator IResourceReader.GetEnumerator()
  {
    return dict.GetEnumerator();
  }
  IEnumerator IEnumerable.GetEnumerator()
  {
    return dict.GetEnumerator();
  }
  public MyResourceReader(string resName)
  {
    fResName = resName;
    dict = new Hashtable();
    dict.Add("Greeting", "Hello");
    dict.Add("Program", "My Program");
    dict.Add("Test Resource", "www.nfex.ru");
  }
}
class Test {
  public static void Main() {
    MyResourceReader reader = new MyResourceReader("MyResources");
    IDictionaryEnumerator dict = ((IResourceReader)reader).GetEnumerator();
    while ( dict.MoveNext() )
    {
     string s = (string)dict.Key;
     if ( s == "Greeting" )
       Console.WriteLine("{0}", dict.Value);
    }
  }
}


Generate resource file with image

  using System;
  using System.Resources;
  using System.Drawing;
  using System.Windows.Forms;
  using System.Reflection;
  class ResourceGenerator
  {
    static void Main(string[] args)
    {
      ResourceWriter rw;
      rw = new ResourceWriter("myResources.resources");
      rw.AddResource("anImage", new Bitmap("winter.jpg"));
      rw.AddResource("welcomeString", "www.nfex.ru");
      rw.Generate();
    }
  }


Load Rescouce BMP image

  using System;
  using System.Drawing;
  using System.Collections;
  using System.ruponentModel;
  using System.Windows.Forms;
  using System.Data;
  using System.Resources;
  public class MainForm : System.Windows.Forms.Form
  {
    private System.Windows.Forms.PictureBox pictureBox1;
    private System.Windows.Forms.Button btnLoadRes;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.PictureBox pictureBox2;
    public MainForm()
    {
      InitializeComponent();
      CenterToScreen();
    }
    private void InitializeComponent()
    {
      System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
      this.pictureBox2 = new System.Windows.Forms.PictureBox();
      this.pictureBox1 = new System.Windows.Forms.PictureBox();
      this.btnLoadRes = new System.Windows.Forms.Button();
      this.label1 = new System.Windows.Forms.Label();
      this.SuspendLayout();
      // 
      // pictureBox2
      // 
      this.pictureBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
      this.pictureBox2.Location = new System.Drawing.Point(176, 72);
      this.pictureBox2.Name = "pictureBox2";
      this.pictureBox2.Size = new System.Drawing.Size(32, 32);
      this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
      this.pictureBox2.TabIndex = 5;
      this.pictureBox2.TabStop = false;
      // 
      // pictureBox1
      // 
      this.pictureBox1.Image = ((System.Drawing.Bitmap)(resources.GetObject("pictureBox1.Image")));
      this.pictureBox1.Location = new System.Drawing.Point(176, 16);
      this.pictureBox1.Name = "pictureBox1";
      this.pictureBox1.Size = new System.Drawing.Size(32, 32);
      this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
      this.pictureBox1.TabIndex = 1;
      this.pictureBox1.TabStop = false;
      // 
      // btnLoadRes
      // 
      this.btnLoadRes.Location = new System.Drawing.Point(8, 80);
      this.btnLoadRes.Name = "btnLoadRes";
      this.btnLoadRes.Size = new System.Drawing.Size(144, 23);
      this.btnLoadRes.TabIndex = 4;
      this.btnLoadRes.Text = "Load Happy dude!";
      this.btnLoadRes.Click += new System.EventHandler(this.btnLoadRes_Click);
      // 
      // label1
      // 
      this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold);
      this.label1.Location = new System.Drawing.Point(8, 16);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(152, 40);
      this.label1.TabIndex = 0;
      this.label1.Text = "Here is the image:";
      // 
      // MainForm
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(235, 128);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.pictureBox2,
                                      this.btnLoadRes,
                                      this.pictureBox1,
                                      this.label1});
      this.Name = "MainForm";
      this.Text = "Resource Loader";
      this.ResumeLayout(false);
    }
    static void Main() 
    {
      Application.Run(new MainForm());
    }
    private void btnLoadRes_Click(object sender, System.EventArgs e)
    {
      ResourceManager resources = new ResourceManager (typeof(MainForm));
      
      this.pictureBox2.Image = 
        ((System.Drawing.Bitmap)(resources.GetObject("pictureBox1.Image")));
      resources.ReleaseAllResources();  
    }
      
  }


Reading resources

using System;
using System.Resources;
using System.Collections;
public class Test {
  public static void Main(string[] args) {
     ResourceReader reader = new ResourceReader("English.resources");
     IDictionaryEnumerator en = reader.GetEnumerator();
     while (en.MoveNext()) {
        Console.WriteLine("Resource Name: [{0}] = {1}", en.Key, en.Value );
     }
     reader.Close();
  }
}


Read Resource for difference langauges

using System;
using System.Resources;
using System.Collections;
public class Test {
  public static void DisplayGreeting( string resName ) {
    try {
      ResourceReader reader = new ResourceReader(resName+".resources");
      IDictionaryEnumerator dict = reader.GetEnumerator();
      while ( dict.MoveNext() ) {
        string s = (string)dict.Key;
        if ( s == "Greeting" )
          Console.WriteLine("{0}", dict.Value);
        }
    } catch ( Exception e ) {
        Console.WriteLine("Exception creating manager {0}", e );
        return;
    }
  }
  public static void Main(string[] args) {
    DisplayGreeting("Eng");
    DisplayGreeting("Span");
    DisplayGreeting("French");
  }
}


Resource file generator application for difference languages

using System;
using System.Resources;
class LanguageResourceWriter {
  public static void WriteEnglishResources()
  {
    ResourceWriter rw = new ResourceWriter("Eng.resources");
    rw.AddResource("Greeting", "Hello");
    rw.Generate();
    rw.Close();
  }
  public static void WriteSpanishResources()
  {
    ResourceWriter rw = new ResourceWriter("Span.resources");
    rw.AddResource("Greeting", "Hola");
    rw.Generate();
    rw.Close();
  }
  public static void WriteFrenchResources()
  {
    ResourceWriter rw = new ResourceWriter("French.resources");
    rw.AddResource("Greeting", "Bonjour");
    rw.Generate();
    rw.Close();
  }
  public static void Main()
  {
    WriteEnglishResources();
    WriteSpanishResources();
    WriteFrenchResources();
  }
}


ResX Resource Writer

using System;
using System.Globalization;
using System.Resources;
using System.Collections;
using System.Drawing;
class Class1 {
  static void Main(string[] args) {
         ResXResourceWriter RwX = new ResXResourceWriter("nfex.resx");
         RwX.AddResource("key 1", "First value");
         RwX.AddResource("key 2", "Second value");
         RwX.AddResource("key 3", "Third value");
         // add an image to the resource file
         Image img = Image.FromFile("winter.jpg");
         RwX.AddResource("winter.jpg", img);
         RwX.Generate();
         RwX.Close();
         ResXResourceReader RrX = new ResXResourceReader("nfex.resx");
         IDictionaryEnumerator RrEn = RrX.GetEnumerator();
         while (RrEn.MoveNext())
         {
            Console.WriteLine("Name: {0} - Value: {1}", 
               RrEn.Key.ToString().PadRight(10, " "), 
               RrEn.Value);
         }
         RrX.Close();
   }
}


Save and load image from resource file

  using System;
  using System.Resources;
  using System.Drawing;
  using System.Windows.Forms;
  using System.Reflection;
  class ResourceGenerator
  {
    static void Main(string[] args)
    {
      ResourceWriter rw;
      rw = new ResourceWriter("myResources.resources");
      rw.AddResource("anImage", new Bitmap("winter.jpg"));
      rw.AddResource("welcomeString", "www.nfex.ru");
      rw.Generate();
      try
      {
          ResourceManager rm = new ResourceManager ("myResources", Assembly.GetExecutingAssembly());
    
          PictureBox p = new PictureBox();
          Bitmap b = (Bitmap)rm.GetObject("anImage");      
          p.Image = (Image)b;
          p.Height = b.Height;
          p.Width = b.Width;
          p.Location = new Point(10, 10);
          
          // Load string resource.
          Label label1 = new Label();
          label1.Location = new Point(50, 10);
          label1.Font = new Font( label1.Font.FontFamily, 12, FontStyle.Bold);
          label1.AutoSize = true;
          label1.Text = rm.GetString("welcomeString");  
        
          // Build a Form to show the resources.
          Form f = new Form();
          f.Height = 100;
          f.Width = 370;
          f.Text = "These resources are embedded in the assembly!";
    
          // Add controls & show Form.
          f.Controls.Add(p);
          f.Controls.Add(label1);
          f.ShowDialog();
      }
      catch(Exception e)
      {
        Console.WriteLine(e.ToString());
      }
    }
  }


Save and read value from resx resource file

  using System;
  using System.Resources;
  using System.Drawing;
  using System.Collections;
  using System.Windows.Forms;
  using System.Resources;
  class ResourceGenerator
  {
    static void Main(string[] args)
    {
      ResXResourceWriter w = new ResXResourceWriter("ResXForm.resx");
      Image i = new Bitmap("winter.jpg");
      w.AddResource("myImage", i);
      w.AddResource("welcomeString", "www.nfex.ru");
      w.Generate();
      w.Close();        
        
      // Make a resx reader.
      ResXResourceReader r = new ResXResourceReader("ResXForm.resx");
      
      IDictionaryEnumerator en = r.GetEnumerator();
      while (en.MoveNext()) 
      {
        Console.WriteLine("Value:" + en.Value.ToString(), "Key: " + en.Key.ToString());
      }
      r.Close();
    }
  }


Save Image file to resource file

using System;
using System.Globalization;
using System.Resources;
using System.Collections;
using System.Drawing;
class Class1 {
  static void Main(string[] args) {
         ResXResourceWriter RwX = new ResXResourceWriter("nfex.resx");
         RwX.AddResource("key 1", "First value");
         RwX.AddResource("key 2", "Second value");
         RwX.AddResource("key 3", "Third value");
         // add an image to the resource file
         Image img = Image.FromFile("winter.jpg");
         RwX.AddResource("winter.jpg", img);
         RwX.Generate();
         RwX.Close();
         ResXResourceReader RrX = new ResXResourceReader("nfex.resx");
         IDictionaryEnumerator RrEn = RrX.GetEnumerator();
         while (RrEn.MoveNext())
         {
            Console.WriteLine("Name: {0} - Value: {1}", 
               RrEn.Key.ToString().PadRight(10, " "), 
               RrEn.Value);
         }
         RrX.Close();
   }
}


Writing a resource file programmatically

using System;
using System.Resources;
class Test {
  public static void Main() {
    ResourceWriter rw = new ResourceWriter("English.resources");
    rw.AddResource("Name", "Test");
    rw.AddResource("Ver", 1.0 );
    rw.AddResource("Author", "www.nfex.ru");
    rw.Generate();
    rw.Close();
  }
}