如何在运行时将更改应用于resource.resx文件(用于更改语言)



如何在运行时将更改应用于resource.resx文件我的代码如下,我的问题是资源文件是资源。resx正在更改,但我只有在第二次重新加载后才能得到它

            string xmlPath = Server.MapPath("~/XMLFile1.xml");
            string resourcePath = Server.MapPath("~/LocalResource/Resource.sv-SE.resx");
            System.Xml.XmlTextReader reader = new XmlTextReader(xmlPath);
            ResXResourceWriter writer = new ResXResourceWriter(resourcePath);
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "string")
                    writer.AddResource(reader.GetAttribute("name"), reader.ReadString());
            }
            writer.Generate();
            writer.Close();

   //here I set it to Thread.CurrentThread.CurrentUICulture = new CultureInfo("sv-SE");     
        CultureHelper.CurrentCulture = id;
        //
        // Cache the new current culture into the user HTTP session. 
        //
        Session["CurrentCulture"] = id;
        //
        // Redirect to the same page from where the request was made! 
        //
        return Redirect(Request.UrlReferrer.ToString());
    }

您不必更改文件
您必须创建多个具有不同区域性的资源文件
例如Message.resx、Message.fa.resx、Message.fr.resx
visualstudio可以检测当前区域性并加载合适的文件
要实现多语言特性,有两种方法
1-使用基本控制器和继承

public class BaseController : Controller
{
    private const string LanguageCookieName = "MyLanguageCookieName";
    protected override void ExecuteCore()
    {
        var cookie = HttpContext.Request.Cookies[LanguageCookieName];
        string lang;
        if (cookie != null)
        {
            lang = cookie.Value;
        }
        else
        {
            lang = ConfigurationManager.AppSettings["DefaultCulture"] ?? "fa-IR";
            var httpCookie = new HttpCookie(LanguageCookieName, lang) { Expires = DateTime.Now.AddYears(1) };
            HttpContext.Response.SetCookie(httpCookie);
        }
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
        base.ExecuteCore();
    }
}


2-使用属性

public class LocalizationActionFilterAttribute : ActionFilterAttribute
{
    private const string LanguageCookieName = "MyLanguageCookieName";
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var cookie = filterContext.HttpContext.Request.Cookies[LanguageCookieName];
        string lang;
        if (cookie != null)
        {
            lang = cookie.Value;
        }
        else
        {
            lang = ConfigurationManager.AppSettings["DefaultCulture"] ?? "fa-IR";
            var httpCookie = new HttpCookie(LanguageCookieName, lang) { Expires = DateTime.Now.AddYears(1) };
            filterContext.HttpContext.Response.SetCookie(httpCookie);
        }
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
        base.OnActionExecuting(filterContext);
    }
}

区域性代码列表

最新更新