1.创建两个资源文件
Resource.en-US.resx Resource.zh-CN.resx 注意中间部分每种语言文件名固定,后缀名是.resx,首部分是自定义的名字
2.创建读写工具类
上面两个资源文件都是在Utility项目集中
当另一个含有UI的项目调用次Utility里的资源时需要引用此项目,然后编译后在UI的项目debug中会自动生成嵌入的文件如:
debug\en-US\Utility.resources.dll 和debug\zh-CN\Utility.resources.dll
注意:
ResourceManager rm = new ResourceManager("Utility.Resource", Assembly.GetExecutingAssembly());的调用就要以命名空间+资源文件首部名的形式。
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
namespace WindowsFormsApplication1
{
public class Utility
{
/// <summary>
/// Set current culture by name
/// </summary>
/// <param name="name">name</param>
public static void SetCurrentCulture(string name)
{
if (string.IsNullOrEmpty(name))
{
name = "CN";
}
Thread.CurrentThread.CurrentCulture = new CultureInfo(name);
}
/// <summary>
/// Get string by id
/// </summary>
/// <param name="id">id</param>
/// <returns>current language string</returns>
public static string GetString(string id)
{
string strCurLanguage = "";
try
{
ResourceManager rm = new ResourceManager("Utility.Resource", Assembly.GetExecutingAssembly());
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
strCurLanguage = rm.GetString(id, ci);
}
catch(Exception ee)
{
strCurLanguage = "No id:" + id + ", please add.";
}
return strCurLanguage;
}
}
}
3.界面
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Utility.SetCurrentCulture("zh-CN");
this.textBox1.Text = Utility.GetString("a1");
}
private void button2_Click(object sender, EventArgs e)
{
Utility.SetCurrentCulture("en-US");
this.textBox1.Text = Utility.GetString("a1");
}
}
}