I’m using the following right now:
foreach (string file in files) {
switch (filetype.Value) {
case "ReadFile":
ReadFile(file);
break;
case "ReadMSOfficeWordFile":
ReadMSOfficeWordFile(file);
break;
case "ReadMSOfficeExcelFile":
ReadMSOfficeExcelFile(file);
break;
case "ReadPDFFile":
ReadPDFFile(file);
break;
}
}
It works, but it feels kinda wrong. The Python way would be something more like this:
foreach string file in files:
filetype.Value(file)
I have a really hard time imagining that C# can’t do something like this. It may be that my Google skills are bad, but I can’t seem to figure it out.
SOLUTION
public static readonly IDictionary<string, Action<string>> FileTypesDict = new Dictionary<string,Action<string>> {
{"*.txt", ReadFile},
{"*.doc", ReadMSOfficeWordFile},
{"*.docx", ReadMSOfficeWordFile},
{"*.xls", ReadMSOfficeExcelFile},
{"*.xlsx", ReadMSOfficeExcelFile},
{"*.pdf", ReadPDFFile},
};
foreach (KeyValuePair<string, Action<string>> filetype in FileTypesDict) {
string[] files = Directory.GetFiles(FilePath, filetype.Key, SearchOption.AllDirectories);
//System.Reflection.MethodInfo ReadFileMethod = ReadFile.GetType().GetMethod(filetype.Value);
foreach (string file in files) {
FileTypesDict[filetype.Key](file);
}
}
You can do it with some preparation using delegates, like this:
When it is time to call your action, do it as follows: