IN C # how to get file names starting with a prefix from a resource folder

how to access a text file based on its prefix

var str = GrvGeneral.Properties.Resources.ResourceManager.GetString(configFile + "_Nlog_Config"); var str1 = GrvGeneral.Properties.Resources.ResourceManager.GetObject(configFile + "_Nlog_Config"); 

where configfile is the prefix of resource files A and B.

Based on the contents of the configuration file (prefix), you need to access the resource files A and B.

+4
source share
2 answers

Use the DirectoryInfo () class. Then you can call GetFiles with a search pattern.

 string searchPattern = "abc*.*"; // This would be for you to construct your prefix DirectoryInfo di = new DirectoryInfo(@"C:\Path\To\Your\Dir"); FileInfo[] files = di.GetFiles(searchPattern); 

Edit: If you have a way to create the actual file name you are looking for, you can go directly to the FileInfo class , otherwise you will have to iterate over the corresponding files in my previous example.

+8
source

Your question is rather vague ... but it looks like you want to get the text content of an embedded resource. You usually do this using Assembly.GetManifestResourceStream . You can always use LINQ with Assembly.GetManifestResourceNames() to find the name of the embedded file that matches the pattern.

The ResourceManager class is often used to automatically retrieve localized string resources, such as labels and error messages in different languages.

update: a more general example:

 internal static class RsrcUtil { private static Assembly _thisAssembly; private static Assembly thisAssembly { get { if (_thisAssembly == null) { _thisAssembly = typeof(RsrcUtil).Assembly; } return _thisAssembly; } } internal static string GetNlogConfig(string prefix) { return GetResourceText(@"Some\Folder\" + prefix + ".nlog.config"); } internal static string FindResource(string pattern) { return thisAssembly.GetManifestResourceNames() .FirstOrDefault(x => Regex.IsMatch(x, pattern)); } internal static string GetResourceText(string resourceName) { string result = string.Empty; if (thisAssembly.GetManifestResourceInfo(resourceName) != null) { using (Stream stream = thisAssembly.GetManifestResourceStream(resourceName)) { result = new StreamReader(stream).ReadToEnd(); } } return result; } } 

Using an example:

 string aconfig = RsrcUtil.GetNlogConfig("a"); string bconfigname = RsrcUtil.FindResource(@"b\.\w+\.config$"); string bconfig = RsrcUtil.GetResourceText(bconfigname); 
+2
source

Source: https://habr.com/ru/post/1399012/


All Articles