在Web上進行調查時,我發現獲取文件內置屬性值(如「作者」,「DateLastSaved」或「公司」)的唯一示例看起來像這樣:使用_oledocumentproperties.SummaryProperties實例上的反射通過名稱獲取文件屬性值
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
值,然後,根據該值的切換的情況下,返回相關_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
!
我的問題是:你知道更好的方法來實現我正在尋找的功能嗎?或者你可以調整我最後的代碼提示來通過反射來解決我的問題嗎? 謝謝你們!