Iterating over Word Document Fields using ComAutomationFactory in Silverlight 4

一世执手 提交于 2019-12-05 17:24:12

It certainly isn't a C# issue - VB.NET has the same issue. There is either a bug here or something not documented, but in either case, it seems impossible to declare collection objects.

There is another way around this however, it is to access the individual members of the collection. Here's a sample (in VB.NET) that allows you to iterate through via Fields.Item. (no error checking or shutting down of Word here; my .dotx has two fields - 1) date and 2) author).

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
    Dim wrd As Object = ComAutomationFactory.CreateObject("Word.Application")
    Dim path As String = "C:\Users\me\test.dotx"
    Dim wordDoc As Object = wrd.Documents.Add(path)
    Dim fieldsCount As Integer = wordDoc.Fields.Count
    Dim fieldResults As String = Nothing
    For i As Integer = 1 To fieldsCount
        fieldResults = fieldResults & " " & wordDoc.Fields.Item(i).Result.Text & vbNewLine
    Next
    TextBox1.Text = "Field Results: " & fieldResults
End Sub

Could be something to do with Silverlight 4.0's implementation of the ComAutomationFactory. I don't have VS2K10 Beta 2 so can't check.

Using "dynamic" types works fine in a console app though ...

dynamic oWord = //ComAutomationFactory.CreateObject("Word.Application");
     Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application", true)); 

oWord.Visible = false;

object oTemplatePath = "c:\\vishal.dotx";
dynamic oWordDoc = oWord.Documents.Add(ref oTemplatePath);
dynamic fields = oWordDoc.Fields;

Console.WriteLine("template has {0} merge flds", fields.Count);

//Method 1
Console.WriteLine(string.Join("\n", ((IEnumerable)oWordDoc.Fields).Cast<dynamic>().Select(x=>(string)x.Result.Text).ToArray()));

//Method 2
foreach (dynamic fld in fields)
 Console.WriteLine(fld.Result.Text);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!