24

I really don't know/have the answer, knowledge to find a resource value using a key from a resx file in a assembly using c#.(or may be i am ignorant).

What would be the fastest code, way i can retrieve string values or values using a key from a resource file which is embedded as resource in a assembly. I am storing friendly messages for exceptions in the resource file and would like to use them when required.

Does a static class exist for this purpose?

Are there open source mature projects i can use for this?

Jens Björnhager
  • 5,632
  • 3
  • 27
  • 47
Deeptechtons
  • 10,945
  • 27
  • 96
  • 178

7 Answers7

47

If the resource is in the same assembly as the code, then the following will do:

String resourceValue = MyAssemblyNameSpace.Properties.Resources.ResourceName

Taken from this SO answer.

Community
  • 1
  • 1
herzbube
  • 13,158
  • 9
  • 45
  • 87
  • Just an easier way as going through this resourceManager-thing. Thanks. – C4d Jun 17 '15 at 10:54
  • This have the benefit of not using Magic strings. Also, you will be able to simply write Resources.ResourceName in your code if you add "using MyAssemblyNameSpace.Properties;" to your code. – Maxter Sep 03 '19 at 14:13
  • will this work with localization? i.e. when I have Resources.de.resx and Resources.en.resx with the respective localized strings, wont I need the ResourceManager? – Tanque May 13 '20 at 12:40
20
Assembly assembly = this.GetType().Assembly;
ResourceManager resourceManager = new ResourceManager("Resources.Strings", assembly);
string myString = resourceManager.GetString("value");
sblom
  • 26,911
  • 4
  • 71
  • 95
  • 3
    Hi, thanks for the code. Doesn't the lin1 employ reflection? how performant can this be. – Deeptechtons Jan 24 '12 at 05:29
  • 2
    @Deeptechtons, Yeah--sorta does. I actually don't think GetType().Assembly is all that slow, but even if it is, presumably you'd just do that one time early on in your program. The idea is that you'd stash `resourceManager` somewhere in your app's main object or something and just use it when you need to get a string. – sblom Jan 24 '12 at 05:32
  • Does a assembly provide events early in lifecycle, so that by the time exception occurs i just get to retrieve the string rather than instantiating each time. – Deeptechtons Jan 24 '12 at 05:33
  • Gives me a `MissingManifestResourceException`. – Ivan Mar 17 '14 at 16:30
  • which way is faster, above one OR "MyAssemblyNameSpace.Properties.Resources.ResourceName". is first way loaded on demand from resc-file everytime we need it and second way loaded on start only? – mayur Rathod Mar 30 '16 at 08:25
  • Dear God, why was this so hard? Samples with reading streams, etc. – dudeNumber4 Aug 29 '18 at 18:53
14
string val = Resources.ResourceManager.GetString("resource_name");

Given "resource_name" you can retrieve resource value.

bluish
  • 26,356
  • 27
  • 122
  • 180
SurenSaluka
  • 1,534
  • 3
  • 18
  • 36
4
 var thread = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
            var culture = new CultureInfo(thread);
            var resourceManager = new ResourceManager(typeof(Resources.Resource));
            string value = resourceManager.GetString(name, culture);
Anup Shetty
  • 571
  • 8
  • 10
  • That's the one I was looking for! I always try to avoid strings like the other ResourceManager constructors use. – madannes Nov 28 '17 at 18:47
  • Best answer. Not only does it avoid hard coded strings, but it also uses cultural info for multi-language support – tval Jan 09 '20 at 00:11
4

you can use ResourceManger to get the string value from Assembly

Get Resource from Assembly

ResourceManager ResManager= new ResourceManager("yourResource", 
            Assembly.GetExecutingAssembly());
String strResourveValue = ResManager.GetString("YourStringKey");
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
3

When I made a new project for my unit tests of type C# class library called UnitTests, I right clicked and Added a new Resource. I named that UnitTestsResources. I added 2 strings to that resource. I was then able to conveniently able to access them like this

UnitTestsResources.NoDeviceRequireMsg

I was curious how that worked so i pulled up the code behind the resource file and it makes sense. Visual Studio made a internal class with static accessors.. It looks like this for me

[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class UnitTestsResources {

    //Some auto generated code

    /// <summary>
    ///   Looks up a localized string similar to OPOS Device is required for test.
    /// </summary>
    internal static string DeviceRequireMsg {
        get {
            return ResourceManager.GetString("DeviceRequireMsg", resourceCulture);
        }
    }

    /// <summary>
    ///   Looks up a localized string similar to OPOS Device must not be installed for test.
    /// </summary>
    internal static string NoDeviceRequireMsg {
        get {
            return ResourceManager.GetString("NoDeviceRequireMsg", resourceCulture);
        }
    }
}

Since it is only for my unit tests I am content with this. Hope it helps someone else.

Robert Snyder
  • 2,399
  • 4
  • 33
  • 65
2

To improve on Herzbube's answer I will show how I implemented this...

Rather than creating projects or folders for the resource file, just right click your project and do add -> new item, then choose resources file. Open the resources file stick in your strings, save as a useful name, and navigate over to C# where you want to use them, then it is just:

String resourceValue = MyProjectName.MyResourceFileName.MyResourceRowItem;

If that isnt working pay attention to the access modifier drop down when inside your resx file.

Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
Chris
  • 968
  • 16
  • 27