Instance is read-only Exception while changing culture in asp.net
Asked Answered
O

1

6

I try to implement multicultural application where users able to change language, date format and etc. I wrote core but it returns Exception: System.InvalidOperationException: Instance is read-only.

switch (culture)
    {
        case SystemCulture.English:
                Thread.CurrentThread.CurrentCulture = new CultureInfo(CultureCodes.English);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(CultureCodes.English);
                break;
                        //another cultures here
    }
    switch (cultureFormat)
    {
        case SystemDateFormat.European:
                  var europeanDateFormat = CultureInfo.GetCultureInfo(CultureCodes.Italian).DateTimeFormat;
                  Thread.CurrentThread.CurrentCulture.DateTimeFormat = europeanDateFormat;
                  Thread.CurrentThread.CurrentUICulture.DateTimeFormat = europeanDateFormat;
                  break;
    //another cultures here
    }
        

I found some information on internet and i have to use new instance object of my culture, i changed my code just adding:

CultureInfo myCulture;

switch (culture)
{
       case SystemCulture.English:
            myCulture= new CultureInfo(CultureCodes.English);
            break;
}

and bellow, out of switch :

Thread.CurrentThread.CurrentCulture = cultureInfo;

I'm not familiar with Threads and i'm not sure if i used is correctly. Could you please suggest me how to do this it right way ?

Octillion answered 5/7, 2019 at 8:18 Comment(0)
A
10

You get the Instance is read-only error because you are trying to alter a property on a a read-only culture, via the code below.

Thread.CurrentThread.CurrentCulture.DateTimeFormat = europeanDateFormat;

You can check whether a culture is readonly via its IsReadOnly property; the built-in ones are.

Instead, you must make a clone/copy of the currently active culture, apply any changes on that clone and assign that one to the CurrentCulture and/or CurrentUICulture of the current thread.

var clone = Thread.CurrentThread.CurrentCulture.Clone() as CultureInfo;
clone.DateTimeFormat = CultureInfo.GetCultureInfo("it").DateTimeFormat;

Thread.CurrentThread.CurrentCulture = clone;
Thread.CurrentThread.CurrentUICulture = clone; 
Albeit answered 5/7, 2019 at 21:34 Comment(2)
Thanks, i just added checking if(Thread.CurrentThread.CurrentCulture.IsReadOnly){}Octillion
Actually both, the CultureInfo and the format infos (DateTimeFormat, NumberFormat) can be read-only (e.g. if you want to change the decimal separator or an existing NumberFormat).Icebreaker

© 2022 - 2024 — McMap. All rights reserved.