在目录中搜索遵循特定命名约定的文件的好方法

本文关键字:命名约定 文件 方法 搜索 | 更新日期: 2023-09-27 18:16:36

我的应用程序允许客户端手动指定80张稍后将使用的图像。但是,我也提供了自动查找和加载这些图像文件的功能,只要它们遵循特定的命名约定。

例如,这些文件的命名约定如下:

*ClientName*_*ImageName*.png

只允许PNG文件,ImageName是应用程序定义的名称集。ClientName被忽略,因为它是客户端定义的。

我正在添加更多的图像,并意识到我目前的处理方式是不可行的。

目前我得到指定目录中所有扩展名为PNG的文件。

然后,我的代码如下(示例):
if (StringContains(currFile, "Tree"))
{
    // assign image "Tree"
}
else if (StringContains(currFile, "Bush"))
{
    // assign image "Bush"
}
...etc

我的StringContains函数简单地执行String.IndexOf(currFile, StringComparison.CurrentCultureIgnoreCase),如果结果为>= 0则返回true。

这种方法的第一个问题是无穷无尽的if/else if语句。这是不可控的。

第二个问题是,如果我有一个名为TreeMaple的图像。我现在需要改变我的if语句查找"树"图像为:

if (StringContains(currFile, "Tree") && !StringContains(currFile, "Maple"))

你可以想象,当你添加更多的图像名称,如"TreeMapleFall","TreeMapleWinter","TreeMapleWinterSnow"等,这是多么疯狂,这就是我打算做的。

我如何使这段代码更简单,可维护和更容易阅读?

在目录中搜索遵循特定命名约定的文件的好方法

这样做可能更容易:

string pattern = @"[^_]+_([^_]+)'.png";  // Regex pattern to capture *ImageName*
Regex regex = new Regex(pattern);
Match match = regex.Match(currFile);
if (match.Success)                       // If image abides by the format
{
    switch (match.Value) {               // Switch on the *ImageName*
        case "Tree":
            // Logic
            break;
        case "Bush":
            // Logic
            break;
        case "Maple":
            // Logic
            break;
    }
}

或使用委托:

Dictionary<string, Action> imageActions = new Dictionary<string, Action>();
if (match.Success && imageActions.ContainsKey(match.Value))   // If image abides by the format and a delegate exists for handling that image name
    imageActions[match.Value]();
// usage
imageActions.Add("Tree", () => { /* Logic */ });