Nap
Nap

Reputation: 8266

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.

Upvotes: 5

Views: 12866

Answers (3)

Davin Tryon
Davin Tryon

Reputation: 67296

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;
    } 
}

Upvotes: 2

Haris Hasan
Haris Hasan

Reputation: 30097

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

Upvotes: 4

pennyrave
pennyrave

Reputation: 770

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.

Upvotes: 12

Related Questions