使用_ onledocumentproperties.SummaryProperties实例上的Reflection按名称获取文件属性值

时间:2016-03-04 13:54:31

标签: c# file system.reflection

在网上调查,我发现获取文件内置属性值的唯一示例如“作者”,“DateLastSaved”或“公司”如下所示:

string filePath= @"C:\Users\ME\Desktop\PaperSpecs.docx";
DSOFile.OleDocumentProperties file = new DSOFile.OleDocumentProperties();
file.Open(filePath, false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);

Console.WriteLine("Author: " + file.SummaryProperties.Author.ToString());
Console.WriteLine("DateLastSaved: " + file.SummaryProperties.DateLastSaved.ToString());
Console.WriteLine("Company: " + file.SummaryProperties.Company.ToString());

让我们考虑通过属性名称来检索一个值...我的意思是实现一个带有两个参数的函数:i)DSOFile.OleDocumentProperties实例; ii)财产名称(string propName)。 我的第一个想法,但我认为“最愚蠢的方式”也包括实现一个检查propName值的switch-case,然后根据该值返回相关的_oledocumentproperties.SummaryProperties属性。那就是:

...
string val= null;
switch(propName)
{
  case case "Author":
   val= file.SummaryProperties.Author.ToString(); break;
  case case "DataLastSaved":
   val= file.SummaryProperties.DataLastSaved.ToString(); break;
  ...
  default: throw new Exception("Property not found");
 }
return val;

但我不喜欢这种解决方案,写作“太长”并且“不容易”保持。也许有更好的方法来实现这个功能......例如使用C#Reflection的强大功能!我处理反射并不是很好,但我试图做那样的事情:

...
Type t = file.SummaryProperties.GetType();
System.Reflection.PropertyInfo p = t.GetProperty(propName);
object value = p == null ? null : p.GetValue(file.SummaryProperties, null);
return value.ToString();

问题是p实例总是null !!!

我的问题是:您是否知道更好的方法来实现我正在寻找的功能?或者你可以通过Reflection调整我的最后一个代码提示来解决我的问题吗?  谢谢你们!

1 个答案:

答案 0 :(得分:0)

Here就是答案......反射不会使用COM对象。