Replace or change field code

We have a following field code in document. We want to replace this field code with another field code. Can you please help me out.
SEQ 3.2.P.5.2- * ARABIC is incorrect field code. This should be replaced with SEQ Figure * ARABIC

Please find attached file. sample incorrect sequence field code.zip (48.2 KB)

@crshekharam,
You can use Range.Replace method to replace text in your document (including field codes). Please check the following code example:

Document doc = new Document(@"C:\Temp\sample incorrect sequence field code.docx");

doc.Range.Replace(@"SEQ 3.2.P.5.2- \* ARABIC", @"SEQ Figure \* ARABIC");
doc.UpdateFields();

doc.Save(@"C:\Temp\sample incorrect sequence field code-output.docx");

@crshekharam Fields in MS Word documents are represented by FieldStart, FieldSeparator and FieldEnd nodes and Run nodes between them. Text between FieldSeparator and FieldEnd represents field value, text between FieldStart and FieldSeparator represents field code.

You can use Field facade class to get access to the field nodes. Foe example, see the following code, that replaces field code:

Document doc = new Document(@"C:\Temp\in.docx");

foreach (Field f in doc.Range.Fields)
{
    if ((f.Start.FieldType == FieldType.FieldSequence) && (f.GetFieldCode().Trim() == @"SEQ 3.2.P.5.2- \* ARABIC"))
    {
        // Run or couple of Run nodes between field start and field end represents field code.
        // Get the first one.
        Run fieldCodeRun = (Run)f.Start.NextSibling;
        // and remove the rest.
        while (fieldCodeRun.NextSibling.NodeType == NodeType.Run)
            fieldCodeRun.NextSibling.Remove();

        // Now set new field code
        fieldCodeRun.Text = "SEQ Figure * ARABIC";
    }
}

doc.Save(@"C:\Temp\out.docx");
1 Like