How to get .resx string value from partial name?

B R 21 Reputation points
2021-07-20T03:19:54.987+00:00

Hi all, I'm creating an application that I would like to Localize down the road and so I've put every string in a Resources.resx file. I'm struggling to find an elegant solution to getting error message strings. As of right now, I pass an enum around to reference which error has occurred, then use that enum to lookup the strings I need just before displaying.

With everything in the .resx file, the problem is that we don't know the error until it occurs, so I need a way to dynamically locate the correct strings rather than hardcode them. I could use a switch statement with the enum as the arg, but this feels sloppy. Here's an example:

switch(errorCode)
{
   case error1:
       error.errorName = Resources.Error1_NoDevicesName;
       error.errorDesc = Resources.Error1_NoDevicesDescription;
       break;

    case error2:
       error.errorName = Resources.Error2_DeviceConnectionName;
       error.errorDesc = Resources.Error2_DeviceConnectionDescription;
       break;

}

However, I'm wondering if it would be possible to search by a partial name instead, where we look for a name that starts with "Error" + "errorCode.ToString()" and ends with "Name"? Or perhaps there's a better way to do this?

EDIT: No clue what is going on with the formatting

Developer technologies | Windows Presentation Foundation
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Viorel 125.7K Reputation points
    2021-07-21T18:50:57.027+00:00

    Try something like this:

    int errorCode = 1;
    
    var a = Assembly.GetEntryAssembly( );
    var rm = new ResourceManager( typeof( Properties.Resources ).FullName, a );
    var rs = rm.GetResourceSet( Thread.CurrentThread.CurrentCulture, true, true );
    
    var n = rs.Cast<DictionaryEntry>( ).FirstOrDefault( e => Regex.IsMatch( e.Key.ToString( ), $"Error{errorCode}_.+Name" ) );
    var d = rs.Cast<DictionaryEntry>( ).FirstOrDefault( e => Regex.IsMatch( e.Key.ToString( ), $"Error{errorCode}_.+Description" ) );
    
    string error_name = n.Value.ToString( );
    string error_description = d.Value.ToString( );
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.