簡體   English   中英

從相同解決方案C#的另一個項目訪問資源文件

[英]Accessing Resource files from another project of same solution C#

我有一個正在解決的Globalization項目,還有另一個MainProject 在全球化下,有2個資源文件, Resources.resxResources.ar.resx 這兩個文件具有相同的密鑰。 我想根據我在model(API)中獲得的語​​言輸入來輸出結果。

聲明為全局: ResourceManager rm;

然后我有此功能,它將檢查從模型輸入的語言,並相應地選擇資源文件。

private void CheckResourceManager(string lang)
{                    
    if (lang =="EN")
    {
        rm = new ResourceManager(
            "Globalization.Resources", 
            Assembly.GetExecutingAssembly());
    }
    else
    {
        rm = new ResourceManager(
            "Globalization.Resources.ar", 
            Assembly.GetExecutingAssembly());
    }
}

我首先在Api函數中檢查CheckResourceManager(model.Language); 當需要消息時,則throw new Exception(rm.GetString("WrongUserName"));throw new Exception(rm.GetString("WrongUserName"));

現在的問題是函數中的"Globalization.Resources.ar"無法讀取資源,因為它找不到文件;我應該在這里使用什么。 如果我在同一項目中添加資源文件,那么它將起作用。 請告知。 謝謝


正確的方法是從下面的答案,但對我來說,這種方法工作正常。

宣告:

ResourceManager rm;
CultureInfo originalCulture = CultureInfo.CurrentCulture;
Assembly localizeAssembly = Assembly.Load("Globalization");

將該功能更改為:

private void CheckResourceManager(string lang)
{
    if (lang =="EN")
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = originalCulture;
        rm = new ResourceManager("Globalization.Resources", localizeAssembly);
    }
    else
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("ar");
        rm = new ResourceManager("Globalization.Resources", localizeAssembly);
    }
}

最后,當我需要獲得一些價值時:

throw new Exception(rm.GetString("WrongUserName",CultureInfo.CurrentCulture));

謝謝。

ResourceManager的全部重點是根據當前線程的UI文化切換到不同的文化。 您無需創建單獨的函數即可。 它不會明確閱讀本地化的文化-它是基於約定的。 要控制當前線程的UI文化,您需要在授權過濾器中對其進行顯式設置:

System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("ar")

另外,傳遞ExecutingAssembly意味着您正在傳遞頂級程序集,而該程序集很可能不是您的資源所在的程序集。您應該在程序集內使用一種類型來獲取Assembly實例:

new ResourceManager(
        "Globalization.Resources", 
        typeof(ClassWithinResourcesAssembly).Assembly)

有關如何使用ResourceManager的更多信息,請參見以下文檔:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM