ranjith
ranjith

Reputation: 199

How to read MS word form fields using c#.net

I tried to read the word document which includes text and form fields. I need to read all text and fields in the document. But the below code always return empty value. It never entering the foreach loop. I don't know what is the issue as there is no error while built. But I didn't get the output. I write it in c# .net 4.6.2 and it will be used as a library file. Is there anything wrong with the code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;
using System.Activities;
using System.ComponentModel;
namespace WordExer
{
  public class WordExer : CodeActivity
  {
    [Category("Input")]
    public InArgument<string> AVal { get; set; }

    [Category("Output")]
    public OutArgument<string> CVal { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
        var a = AVal.Get(context);
        string text = "";
         Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document doc = word.Documents.Add(a);

        doc.Activate();

        foreach (FormField field in doc.FormFields)
        {
            Console.WriteLine(field.Range.Text);
            text += field.Range.Text;
        }
        CVal.Set(context, text);
        word.Quit();
    }  
  }
}

Upvotes: 0

Views: 1925

Answers (1)

Apoorva Raju
Apoorva Raju

Reputation: 300

You can try to access them as inline shapes as depicted in below code snippet

 foreach (InlineShape shape in doc.InlineShapes)
 {
       if (shape.OLEFormat != null && shape.OLEFormat.ClassType == "CONTROL Forms.TextBox.1")
       {
              Console.WriteLine("Data :" + shape.OLEFormat.Object.Value);
       }
 }

Upvotes: 1

Related Questions