簡體   English   中英

從資源文件獲取字符串

[英]getting string from resource file

我有以下靜態類用於在我的mvc應用程序中本地化字符串。 我的資源字符串存儲在文件夾中,例如

  • 資源/EnglishStrings.resx
  • 資源/DeutschStrings.resx
 public static string ReadResourceValue(string lang, string key)
    {
        string file = "";
        if (lang == "en")
        {
            file = "LocalizedUIStrings.en-EN.resx";
        }
        else if (lang == "de")
        {
            file = "LocalizedUIStrings.de-DE.resx";
        }

        //value for our return value
        string resourceValue = string.Empty;
        try
        {
            // specify your resource file name 
            string resourceFile = file;
            // get the path of your file
            //string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
            string filePath = @"~/Resources/";
            // create a resource manager for reading from
            //the resx file
            ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
            // retrieve the value of the specified key
            resourceValue = resourceManager.GetString(key);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            resourceValue = string.Empty;
        }
        return resourceValue;
    }
}

這樣, string filePath = @"~/Resources/"; 我無法使用資源字符串訪問文件夾,該怎么辦?

您可以使用Server.MapPath將虛擬路徑映射到物理路徑。 請參閱此MSDN鏈接

var filePath = HttpContext.Current.Server.MapPath(@"~/Resources/");
var projectPath =  Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string filePath = Path.Combine(projectPath, "Resources");

要么

string filePath = Path.Combine(System.IO.Path.GetFullPath(@"..\..\"), "Resources");

暫無
暫無

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

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