Monday, September 13, 2010

How to read Resource files in our code by LINQ to XML ?

Hello friends,

Sorry for such a late post. Currently I am busy in too many works so not getting enough time to talk with you.

Today I am posting an interesting work which is how to read a resource file in our code with the help of LINQ TO SQL.

I can say only one thing which is its simple and easy to use. Just copy paste below code and you will get what to want.

Before code I will explain you that resource file is just like xml which has attributes and value and that particular attributes is your key.



Now we need to fetch value for particular key for a file for this you have to write below code. Where bv_strFileName is your resource file name and bv_strKey is key for which you need value.

Public Shared Function pub_LangaugeValue(ByVal bv_strFile As String, ByVal bv_strKey As String) As String

Try

Dim strValue As String = “”

Dim resxXML As New XDocument

resxXML = XDocument.Load(bv_strFile)

Dim a = From data In resxXML.Root.Descendants(“data”) _

Where data.Attribute(“name”).Value = bv_strKey _

Select New With {.resxA = data.Attribute(“name”).Value, .ResxValue = data.Element(“value”).Value}

If a.Count() > 0 Then

strValue = a.FirstOrDefault().ResxValue.ToString()

Else

strValue = bv_strKey

End If

Return strValue

Catch ex As Exception

Throw ex

End Try

End Function ‘pub_LangaugeValue



Where bv_strFileName is full path name of our resource file and bv_strkey is the key for which we need to find the value.

Below is example how to use it our aspx.

Suppose we want to read LabelResource1.text value in Spanish whose file name is home.aspx.es.resx.



Then we have to call the above function like below.

Response.write(pub_LanguageValue(server.mapPath(“/App_LocalResources/home.aspx.es.resx”),”LabelResource1.text”)

With the help of above code.

We can get key’s value from different resource file.

I Dreamed A Dream

Thanks

Rajat Jaiswal