Enumerating all strings in resx

Posted by Erik Hesselink on Stack Overflow See other posts from Stack Overflow or by Erik Hesselink
Published on 2008-11-10T15:57:29Z Indexed on 2010/04/06 20:23 UTC
Read the original article Hit count: 589

We would like to enumerate all strings in a resource file in .NET (resx file). We want this to generate a javascript object containing all these key-value pairs. We do this now for satellite assemblies with code like this (this is VB.NET, but any example code is fine):

Dim rm As ResourceManager
rm = New ResourceManager([resource name], [your assembly])
Dim Rs As ResourceSet
Rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)
For Each Kvp As DictionaryEntry In Rs
    [Write out Kvp.Key and Kvp.Value]
Next

However, we haven't found a way to do this for .resx files yet, sadly. How can we enumerate all localization strings in a resx file?

UPDATE:

Following Dennis Myren's comment and the ideas from here, I built a ResXResourceManager. Now I can do the same with .resx files as I did with the embedded resources. Here is the code. Note that Microsoft made a needed constructor private, so I use reflection to access it. You need full trust when using this.

Imports System.Globalization
Imports System.Reflection
Imports System.Resources
Imports System.Windows.Forms

Public Class ResXResourceManager
    Inherits ResourceManager

    Public Sub New(ByVal BaseName As String, ByVal ResourceDir As String)
    	Me.New(BaseName, ResourceDir, GetType(ResXResourceSet))
    End Sub

    Protected Sub New(ByVal BaseName As String, ByVal ResourceDir As String, ByVal UsingResourceSet As Type)
    	Dim BaseType As Type = Me.GetType().BaseType
    	Dim Flags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance
    	Dim Constructor As ConstructorInfo = BaseType.GetConstructor(Flags, Nothing, New Type() { GetType(String), GetType(String), GetType(Type) }, Nothing)
    	Constructor.Invoke(Me, Flags, Nothing, New Object() { BaseName, ResourceDir, UsingResourceSet }, Nothing)
    End Sub

    Protected Overrides Function GetResourceFileName(ByVal culture As CultureInfo) As String
    	Dim FileName As String
    	FileName = MyBase.GetResourceFileName(culture)
    	If FileName IsNot Nothing AndAlso FileName.Length > 10 Then
    		Return FileName.Substring(0, FileName.Length - 10) & ".resx"
    	End If
    	Return Nothing
    End Function
End Class

© Stack Overflow or respective owner

Related posts about .NET

Related posts about localization