2012-02-13 41 views
4

我想知道如何从另一个类库中加载字符串资源。这是我的结构。来自不同类库的访问字符串资源

Solution\ 
    CommonLibrary\ 
     EmbeddedResource.resx 
    MainGUI\ 

如果我得到CommonLibrary类的字符串,我只是用EmbeddedResource.INFO_START_MSG但是当我尝试使用类型的字符串资源,不能识别的资源文件。请注意,CommonLibrary已在MainGUI中引用。

我通常这样做。

Solution\ 
    CommonLibrary\ 
    MainGUI\ 
     EmbeddedResource.resx 

但我想在两个项目上使用相同的资源。

回答

11

将对库的引用添加到主应用程序。确保(在资源文件中)“访问修饰符”设置为公共。

参考字符串像这样:

textBox1.Text = ClassLibrary1.Resource1.ClassLibrary1TestString; 

我的名字加到通过右击资源文件,因此“1”。如果您转到类库的属性页面并单击“资源”选项卡,则可以添加名称中不包含数字“1”的默认资源文件。

只要确定你的价值是公开的,并且你在主项目中有参考并且你应该没有问题。

+4

更具体地说,我将resx文件的“自定义工具”属性从“ResXFileCodeGenerator”更改为“PublicResXFileCodeGenerator”。 – Nap 2012-02-14 02:16:24

3

默认情况下,资源类是internal,这意味着它不会在其他程序集中直接可用。尝试将其更改为public。从这一部分你也将必须使资源类中的字符串属性public

2

这是我过去的做法。但是,这可能无法跨程序集工作:

public static Stream GetStream(string resourceName, Assembly containingAssembly) 
{ 
    string fullResourceName = containingAssembly.GetName().Name + "." + resourceName; 
    Stream result = containingAssembly.GetManifestResourceStream(fullResourceName); 
    if (result == null) 
    { 
     // throw not found exception 
    } 

    return result; 
} 


public static string GetString(string resourceName, Assembly containingAssembly) 
{ 
    string result = String.Empty; 
    Stream sourceStream = GetStream(resourceName, containingAssembly); 

    if (sourceStream != null) 
    { 
     using (StreamReader streamReader = new StreamReader(sourceStream)) 
     { 
      result = streamReader.ReadToEnd(); 
     } 
    } 
    if (resourceName != null) 
    { 
     return result; 
    } 
} 
+0

这可能工作,但我这个使用强类型的字符串变量将避免将来的错误情况字符串资源名拼写错误或更改。为努力争取一票。另外我修正了你的代码的缩写。 – Nap 2012-02-14 02:17:58

相关问题