c# 使用资源文件

时间:2022-05-24 02:00:49

1、新建项目

c# 使用资源文件

2、新建资源文件

c# 使用资源文件

3、 代码中使用嵌入资源

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;
using System.IO;
using System.Resources;
using System.Reflection;
using System.Threading;
using System.Globalization;

namespace MyResource
{
public class Utils
{
/// <summary>
///
/// </summary>
/// <param name="name">表示资源文件中的key值</param>
/// <returns></returns>
public static string GetMessage(string name)
{
//baseName:NameSpace+资源文件的名称(扣除.zh-CN.resx,如:Resource.zh-CN.resx,取Resource)
ResourceManager rm = new ResourceManager("MyResource.Resource", Assembly.GetExecutingAssembly());
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
return rm.GetString(name, ci);
}

/// <summary>
///
/// </summary>
/// <param name="name">name表示资源文件中的key值</param>
/// <param name="language">language表示中文或者英文</param>
/// <returns></returns>
public static string GetMessage(string name, string language)
{
ResourceManager rm = new ResourceManager("MyResource.Resource", Assembly.GetExecutingAssembly());
CultureInfo ci = null;
try
{
ci = new System.Globalization.CultureInfo(language);
}
catch (Exception)
{
ci = Thread.CurrentThread.CurrentCulture;
}
return rm.GetString(name, ci);
}
}
}

4、调用代码

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyResource
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
string msg= Utils.GetMessage("t1");
msg = Utils.GetMessage("t1","en-US");
MessageBox.Show(msg);
}

private void button2_Click(object sender, EventArgs e)
{
string msg = Utils.GetMessage("t1");
msg = Utils.GetMessage("t1", "zh-CN");
MessageBox.Show(msg);
}
}
}

这里下载VS2008源代码:https://files.cnblogs.com/files/soyee/MyResource.rar