Search code examples
c#ms-wordoffice-interopword-field

How to get a type of a word field


I have a Word file with different Fields. I would like to know a type of each field. I know that there is a method called Field.GetType() but it is returning something like this : System.__ComObject

But I would like to know what WdFieldType each field has. https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.wdfieldtype?view=word-pia#Microsoft_Office_Interop_Word_WdFieldType_wdFieldIncludeText

The problem is, that I don't know what filed types people uses. And some field types are causing errors, when I am trying to get Result. That's why I would like to exclude those types, but I firstly must know what types there is.

My code:

foreach (string LeitudNimi in Nimed)
{
    foreach (Field f in doc.Fields)
    {
        if (f.Type != WdFieldType.some field that is causing error)
        {
            if (f.Result.Text.ToLower() == LeitudNimi)
            { 
                f.Result.Text = $"{Nimi}"; 
                f.Unlink(); 
            }
        }
    }
}

And to use that code. I firstly planning to do something like this:

foreach (Field f in doc.Fields)
                        {var Type1 = f.GetType()
File.AppendAllText(@"C:\tulemus.txt", $"Field type is: {Type1}" + Environment.NewLine);}

Solution

  • I think you should be checking the value of [f.Type] (reference) just as you are doing in your first code sample. f.GetType() is returning you the C# object type of the instance held by f

    foreach (Field f in doc.Fields)
    {
      File.AppendAllText(@"C:\tulemus.txt", $"Field type is: {f.Type}" + Environment.NewLine);
    }