Skip to content

Instantly share code, notes, and snippets.

@royashbrook
Created June 30, 2014 20:53
Show Gist options
  • Save royashbrook/a74375d367f90f3a3214 to your computer and use it in GitHub Desktop.
Save royashbrook/a74375d367f90f3a3214 to your computer and use it in GitHub Desktop.
iterate over word fields and formfields in LINQPad
void Main()
{
string sPath = @"c:\temp\somedoc.docx";
ShowFields(sPath);
}
//using Microsoft.Office.Interop.Word
void ShowFields(string sPath)
{
//references for the com objects
Application oApp = null;
Document oDoc = null;
try{
//set some ref values we'll need for word
object oPath = sPath;
object oMissing = System.Reflection.Missing.Value;
object oFalse = true;
//spin up word
oApp = new Application();
//hide it - remove this if needed
oApp.Visible = false;
//open the document
oDoc = oApp.Documents.Open(
ref oPath, ref oMissing, ref oMissing, ref oFalse
, ref oMissing, ref oMissing, ref oMissing, ref oMissing
, ref oMissing, ref oMissing, ref oMissing, ref oMissing
, ref oMissing, ref oMissing, ref oMissing, ref oMissing );
//iterate over the fields in a variety of ways
oDoc.Iterate();
//close out the doc
oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
//quit the app
oApp.Quit(ref oMissing, ref oMissing, ref oMissing);
}
catch(Exception ex){
ex.Dump();
}
finally{
//release the interop objects
if (oDoc != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
if (oApp != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oApp);
//null them out
oDoc = null;
oApp = null;
//invoke GC just in case
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
static class myExtensions{
public static void Iterate(this Document oDoc){
(from oField in ((IEnumerable)oDoc.Fields).Cast<Field>()
select new {
Index = oField.Index
, Result = oField.Result.Text
}).Dump();
(from oFormField in ((IEnumerable)oDoc.FormFields).Cast<FormField>()
select new {
Name = oFormField.Name
, Result = oFormField.Result
}).Dump();
foreach (dynamic oField in oDoc.Fields)
Console.WriteLine("{0} - {1}", oField.Index, oField.Result.Text);
foreach(FormField oField in oDoc.FormFields)
Console.WriteLine("{0} - {1}", oField.Name, oField.Result);
foreach(Field oField in oDoc.Fields)
Console.WriteLine("{0} - {1}", oField.Index, oDoc.Fields[oField.Index].Result.Text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment