using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Runtime.InteropServices;
// ... 參考 Microsoft.Office.Interop.Word ...
Word.Application oWord = new Word.Application();
Word._Document oDoc = null;
object oMissing = Missing.Value;
object source = @"DocPath";
object unknown = Type.Missing;
try {
oDoc = oWord.Documents.Open(ref source, ref unknown, ref unknown, ref unknown,
ref unknown, ref unknown, ref unknown, ref unknown,
ref unknown, ref unknown, ref unknown, ref unknown);
object docBuiltInProps = oDoc.BuiltInDocumentProperties;
Type typeProps = docBuiltInProps.GetType();
// 取得作者
string index = "Author";
object docAuthor = typeProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty,
null, docBuiltInProps, new object[] { index });
Type typeAuthor = docAuthor.GetType();
string author = typeAuthor.InvokeMember("Value", BindingFlags.Default | BindingFlags.GetProperty,
null, docAuthor, new object[] {} ).ToString();
MessageBox.Show(author, "Author");
// 取得主題
index = "Subject";
object docSubject = typeProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty,
null, docBuiltInProps, new object[] { index });
Type typeSubject = docSubject.GetType();
string subject = typeSubject.InvokeMember("Value", BindingFlags.Default | BindingFlags.GetProperty,
null, docSubject, new object[] {} ).ToString();
MessageBox.Show(subject, "Subject");
}
finally {
object save = false;
oWord.Quit(ref save, ref unknown, ref unknown);
Marshal.ReleaseComObject(oWord);
}
InvokeMember 避免版本相依,支援 Word 2003 到最新版。BuiltInDocumentProperties 包含:Title, Subject, Author, Keywords, Comments, Template, LastAuthor, RevisionNumber, ApplicationName, LastPrintDate, CreationDate, LastSaveTime, TotalEditingTime, Pages, Words, Characters, Security, Category, Format, Manager, Company, Bytes, Lines, Paragraphs, Slides, Notes, HiddenSlides, MMClips 等。Quit 再 ReleaseComObject,防止 Word 進程殭屍。