Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

resources

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 the configfile is the prefix of the resourcefile A & B .

Based on the configfile contents (prefix) the resource file A & B has to be accessed .

like image 848
Nisha Avatar asked Feb 29 '12 13:02

Nisha


2 Answers

Use the DirectoryInfo class (documentation). Then you can call the 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 of constructing the actual file name you're looking for, you can go directly to the FileInfo class, otherwise you'll have to iterate through the matching files in my previous example.

like image 122
Joel Etherton Avatar answered Nov 01 '22 11:11

Joel Etherton


Your question is rather vague...but it sounds like you want to get the text contents of an embedded resource. Usually you would do that using Assembly.GetManifestResourceStream. You can always use LINQ along with Assembly.GetManifestResourceNames() to find the name of an embedded file matching a pattern.

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

update: A more generalized 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 the example:

string aconfig = RsrcUtil.GetNlogConfig("a");
string bconfigname = RsrcUtil.FindResource(@"b\.\w+\.config$");
string bconfig = RsrcUtil.GetResourceText(bconfigname);
like image 45
Joshua Honig Avatar answered Nov 01 '22 11:11

Joshua Honig