Use filename to determine file type This is legacy, so I'm not really looking for improvements on architectural approach.

Here's what the method does:


Extracts filename from a string containing full file path (passed in as parameter)
Checks to see if the filename extracted is not null or empty or just white spaces
If check in step 2 passes, then it uses naming conventions in the filename, to determine the logical "Type" for the file as follows:


If filename contains __Import__, then setType to Source Data
If filename contains __Export__, then setType to Destination Data
If filename contains __Transform__, then setType to Transformational Data
If none of the conditions from 3.1 through 3.3 are met, then default the "Type" to General.



Is there a way to make the if...else if... else if... block more concise, and elegant without loss of functionality?

private static string GetFileDataType(string fullFileNameWithPath)
{
    // extract filename only
    var fileName = Path.GetFileNameWithoutExtension(fullFileNameWithPath);
    var fileDataType = string.Empty;

    // if filename is not empty
    if (!string.IsNullOrWhiteSpace(fileName))
    {
        // if... else... to determine type of file contents based on file name convention
        // legacy code, so not looking for architectural improvements etc... :)
        if (fileName.Contains("__Import__"))
        {
            fileDataType = "Source Data";
        }
        else if (fileName.Contains("__Export__"))
        {
            fileDataType = "Destination Data";
        }
        else if (fileName.Contains("__Transform__"))
        {
            fileDataType = "Transformational Data";
        }
        else
        {
            fileDataType = "General";
        }
    }

    return fileDataType;
}
I find the cleanest way is to replace the ugly if/else if/else with a dictionary:

private static IDictionary&lt;string, string&gt; FileDataTypes = new Dictionary&lt;string, string&gt;(StringComparer.OrdinalIgnoreCase)
{
    ["Import"] = "Source Data",
    // ..
}


The also not so pretty Contains can be replaced with a nice regex that will grow or shirnk automatically if you add/remove mappings:

private static string GetFileDataType(string fullFileNameWithPath)
{
    var fileName = Path.GetFileNameWithoutExtension(fullFileNameWithPath);
    var fileContentsMatch = Regex.Match(fileName, $"__(?&lt;Type&gt;{string.Join("|", FileDataTypes.Keys)})__", RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
    return
        fileContentsMatch.Success &amp;&amp; FileDataTypes.TryGetValue(fileContentsMatch.Groups["Type"].Value, out var fileDataType) 
            ? fileDataType 
            : FileDataTypes[string.Empty];  
}


Notice that both the dictionary and the regex are case insensitive. You should always make paths case insensitive in Windows. You are lucky that this worked for so long.

(Dislaimer: It's just an example so I was to lazy to implement all the empty/null checks)