Reputation: 3746
I have 3 resource files:
/Resources/Values.en-US.resx
/Resources/Values.es-ES.resx
/Resources/Values.fr-FR.resx
(English, Spanish, French)
From here I want to 'scan' what languages (from these resource files) are available so I can put them in a list and display them to the user for selecting. After releasing my program, people should be able to add more languages. The program will scan for new languages and make them available from a list.
Is there a way to get the files from Resources folder?
Upvotes: 0
Views: 2919
Reputation: 3374
You can iterate through files located under application content directory, then select the resource files, extract the culture fragment from the file name and eventually create a list of cultures.
First, inject the IHostingEnvironment to use the ContentRootPath
property it provides.
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
As long as you keep all your resource files under ./Resources/
directory you should be fine.
Next, create 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;
}
Get the resource file names:
var resoruceFilesInfo = contentDirectoryInfo.GetFiles("*.resx", SearchOption.AllDirectories);
var resoruceFileNames = resoruceFilesInfo.Select(info => info.Name);
All three examples of resource files you provided follow a culture naming pattern. That is, a combination of an ISO 639 two-letter lowercase culture code associated with a language and an ISO 3166 two-letter uppercase subculture code associated with a country or region. For proper culture fragment extraction I suggest using a Regular Expression like this one below:
var regex = new Regex(@"(?<=\.)[a-z]{2}-[A-Z]{2}(?=\.resx$)");
var culturePrefixes = resoruceFileNames.Select(fileName => regex.Match(fileName).Value);
Finally, create a culture collection:
var cultureList = culturePrefixes.Select(prefix => new CultureInfo(prefix));
Upvotes: 1