资源文件夹中的资源文件

时间:2018-12-29 18:18:35

标签: asp.net-core asp.net-core-localization

我有3个资源文件:

/Resources/Values.en-US.resx
/Resources/Values.es-ES.resx
/Resources/Values.fr-FR.resx


(English, Spanish, French)

从这里我想“扫描”哪些语言(来自这些资源文件)可用,因此我可以将它们放在列表中并显示给用户选择。发布我的程序后,人们应该可以添加更多语言。该程序将扫描新语言,并从列表中使它们可用。

是否可以从Resources文件夹中获取文件?

1 个答案:

答案 0 :(得分:1)

您可以遍历应用程序内容目录下的文件,然后选择资源文件,从文件名中提取区域性片段,并最终创建区域性列表。

首先,注入IHostingEnvironment以使用它提供的ContentRootPath属性。

private readonly IHostingEnvironment _hostingEnvironment;

public HomeController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
}

只要将所有资源文件都保存在./Resources/目录下,就可以了。

接下来,创建DirectoryInfo

var contentRootPath = Path.Combine(_hostingEnvironment.ContentRootPath, "Resources");

DirectoryInfo contentDirectoryInfo;
try
{
    contentDirectoryInfo = new DirectoryInfo(contentRootPath);
}
catch (DirectoryNotFoundException)
{
    // Here you should handle "Resources" directory not found exception.
    throw;
}

获取资源文件名:

var resoruceFilesInfo = contentDirectoryInfo.GetFiles("*.resx", SearchOption.AllDirectories);
var resoruceFileNames = resoruceFilesInfo.Select(info => info.Name);

您提供的所有三个资源文件示例均遵循区域性命名模式。即,将与一种语言相关联的ISO 639两字母大写小写文化代码和与某个国家或地区相关联的ISO 3166两字母大写小写文化代码结合在一起。为了正确提取培养物片段,我建议使用以下的Regular Expression

var regex = new Regex(@"(?<=\.)[a-z]{2}-[A-Z]{2}(?=\.resx$)");
var culturePrefixes = resoruceFileNames.Select(fileName => regex.Match(fileName).Value);

最后,创建一个文化集合:

var cultureList = culturePrefixes.Select(prefix => new CultureInfo(prefix));