现在的位置: 首页 > 综合 > 正文

在.net中使用嵌入的资源

2013年11月01日 ⁄ 综合 ⁄ 共 1165字 ⁄ 字号 评论关闭

环境:VS 2008.NET + xp

说明:在.net中使用嵌入的资源

1、在VS中建立一个控制台应用程序项目:Test(此时项目的默认命名空间为:Test

2、Program.cs中添加引用:

using System.Reflection;
using System.Resources;

3、新建资源文件myResource.resx,并添加一个字符串资源,名称和值分别为:"testString","hello"

4、Program.cs源代码:

using System;
using System.Reflection;
using System.Resources;

class Program
{
        static void Main(string[] args)
        {
            //Assembly.GetExecutingAssembly()获取包含当前执行的程序集,返回Assembly对象
            //Test.myResource:其中Test表示工程的命名空间,myResource表示myResource.resx的根名称,即点号有前部分myResource
            Console.WriteLine(Program.LoadAssemblyString(Assembly.GetExecutingAssembly(), "Test.myResource", "teststring"));


            while (Console.Read() != 'q') { }
        }
        private static string LoadAssemblyString(Assembly asm, string baseName, string resourceName)
        {
            try
            {
                ResourceManager rm = new ResourceManager(baseName, asm);
                //IgnoreCase属性指定GetString(System.String)和GetObject(System.String)支持不区分大小写查找,默认为false(区分)
                rm.IgnoreCase = true;
                return rm.GetString(resourceName);
            }
            catch (MissingManifestResourceException)
            {
           
            }
            return null;
        }
}

抱歉!评论已关闭.