Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access String Resource from different Class Library

I would like to know how to load string resource from another class library. Here is my structure.

Solution\
    CommonLibrary\
        EmbeddedResource.resx
    MainGUI\

If I get the string on classes of CommonLibrary I just use EmbeddedResource.INFO_START_MSG but when I try to use typed string resource It cannot recognize the resource file. Note that the CommonLibrary is already referenced in the MainGUI.

I usually do it this way.

Solution\
    CommonLibrary\
    MainGUI\
        EmbeddedResource.resx

But I want to use the same resource on both projects.

like image 771
Nap Avatar asked Feb 13 '12 11:02

Nap


3 Answers

Add the reference to the library to the main application. Make certain that (on the Resources file) the "Access Modifier" is set to public.

Reference the string like so:

textBox1.Text = ClassLibrary1.Resource1.ClassLibrary1TestString;

I added the resource file via right clicking, thus the "1" in the name. If you go to the Properties page for the class library and click on the "Resources" tab, you can add the default resources file, which will not have the numeral "1" in the name.

Just make certain your values are public, and that you have the reference in the main project and you should have no issues.

like image 106
pennyrave Avatar answered Nov 07 '22 01:11

pennyrave


By default the resource class is internal which means it won't be directly available in other assemblies. Try by changing it to public. A part from this you will also have to make the string properties in resource class public

like image 4
Haris Hasan Avatar answered Nov 06 '22 23:11

Haris Hasan


The is the way I've done it in the past. However, this might not work across assemblies:

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;
    } 
}
like image 2
Davin Tryon Avatar answered Nov 07 '22 01:11

Davin Tryon