I am trying to use the Reflection GetProperty
to set the type of OrderBy
I want dynamically. The orderByParam
would have a value such as "Length"
, "Name"
, "CreationTime"
, etc. This will allow me to add the files to a list in the order I want later on. The error I am receiving is:
Object does not match target type
. What am I missing here?
try
{
PropertyInfo propertyInfo = typeof(FileInfo).GetProperty(orderByParam);
var files = Directory.GetFiles(strPath)
.OrderBy(f => propertyInfo.GetValue(orderByParam, null));
//FileInfo(f).CreationTime))
foreach (string str in files)
{
strFiles.Add(Path.GetFileName(str));
}
}
Put it as
PropertyInfo propertyInfo = typeof(FileInfo).GetProperty(orderByParam);
var files = Directory
.EnumerateFiles(strPath)
.OrderBy(f => propertyInfo.GetValue(new FileInfo(f), null));
Since you want property value being read from f
(new FileInfo(f)
, to be exact), not orderByParam