Thursday, February 9, 2012

How to Retrieve Properties from an Office Doc



Is always good to go back to basics and do some low level programming. Office interoperability has been hard before C# 4.0 since the previous version didn’t supported dynamic language features.

C# 4.0 has come a long way since its first version, and is amazing how much support the current version offers you to interoperate with unmanaged code. C# is probably the best language out there that can provide you with a deep support for Windows specific platform features, but that also gives you incredible power to abstract the platform and code your apps independently from it. If you don’t believe me,  take a look at Silverlight running on Mac, Web and Windows (even appearing as a seamless desktop app), Mono having C# running as an open source platform in Linux, and the Moonlight open source Silverlight port.

Anyways, we all now that C# 3.0 was a bit weak in terms of interoperability with unmanaged code and that to access an Office Word document you had to do a lot of hand coding to control all the possible exceptions and interop requirements since office. Now in C# 4.0 you can easily interop with Office files.

The following example shows you how to open an Office Word document, retrieve its properties, close it and then display the document author name on the console.

Remember to make sure the “WordFile.docx” file is on the same directory as your executable (in my case I just added the file to the project and set it to be copied to the output directory) and to add a reference to “Microsoft.Office.Interop.Word” (.NET tab).

As you can see, this is a great improvement from C# 3.0. I’ll be trying to cover more on C# 4.0 features this year since no matter what, after exploring many languages out there, I still thinki C# is on of the best, most powerful and most elegant languages out there, which makes your life as a developer more productive and effectively easier, which by all means should be the goal of every language.

Enjoy and hoe it helps !

No comments:

Post a Comment