mercredi 25 octobre 2017

Build an If Statement by inserting Array Values into the If Condition

I am trying to dynamically build my If statement each time my program runs. Here is how it currently works.

I am reading filenames from a network drive and if the filename contains certain phrases or patterns, then I move them to a folder (we will call it "Bad"). If the filenames do not contain any of those "filters", then it will move them to a folder (we will call it "Good").

I only have 4 filters and it is hardcoded into my If Statement. This usually does not change, but it seems like I am starting to see more "bad" files appear with bad names that are not in my filter list. Here is what my If statement looks like now. I know that educating the users to not do it is a good approach, but we can leave that topic for a different discussion.

if (Path.GetFileName(file).StringContains("123", StringComparison.OrdinalIgnoreCase) || 
Path.GetFileName(file).StringContains("abc", StringComparison.OrdinalIgnoreCase) || 
Path.GetFileName(file).StringContains("xyz", StringComparison.OrdinalIgnoreCase) || 
Path.GetFileName(file).StringContains("890", StringComparison.OrdinalIgnoreCase))

If it matches one of the filters, then move it to "Bad", else move them to "Good".

StringContains is from a custom class called StringExtensionTest. Here is the snippet.

public static class StringExtensionTest
    {
        public static bool StringContains(this string sourcename, string checkname, StringComparison sc)
        {
            return sourcename.IndexOf(checkname, sc) >= 0;
        }
    }

I use an App.config file to store other information and I wanted to create a variable there and add all the filters to that field with a pipe delimiter.

For example:

<add key="Filters" value="123|abc|xyz|890|<any new values afterwards>"/>

Then, I could just use a Split on "Filters" to get the elements and plug each one into

Path.GetFileName(file).StringContains("<some value>", StringComparison.OrdinalIgnoreCase

Then, use a String.Join() to stitch the condition together and finally pass the variable to the IF(). When I attempted to do this, I received a "Cannot implicitly convert type 'string' to 'bool'" at the IF Statement. At this point, I presume that this method will not work.

Is my only option to encapulate the entire IF statement inside a For/Foreach loop and pass the variable 1 by 1? My only concern is that if I have 10,000s+ files to go through and I have several filters, it will have to go through each one. Whereas, if all the conditions are in the IF it just does it once or am I wrong?

Any thoughts and suggestions are appreciated! Thanks.

Aucun commentaire:

Enregistrer un commentaire