We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Renaming MergeFields programatically

I’m trying to rename 1000’s of MergeField names using a program based on the code provided by Aspose at the following link. https://docs.aspose.com/words/net/working-with-fields/

The problems is that in the MergeField object created at this line:

MergeField mergeField = new MergeField(fieldStart);

the Name is truncated to 40 characters. We have lots of fields whose names are longer than 40 characters. I noticed when I open the document in Word it is also showing the mergefield name truncated at 40 but when I edit the field the full name is there. I suspect this is what is making this code fail.

Interestingly, if I get all the field names using doc.MailMerge.GetFieldNames(); they are not truncated.

What can I do about this ? Is this a change I can make in Word ?



Hi Scott,

Thanks for your inquiry. A field in a Word document is a complex structure consisting of multiple nodes that include field start, field code, field separator, field result and field end. Fields can be nested, contain rich content and span multiple paragraphs or sections in a document. The Field class is a “facade” object that provides properties and methods that allow to work with a field as a single object.

Please note that Aspose.Words mimics the same behavior as MS Word does. If you update the mail merge field using MS Word and check the characters of mail merge field, MS Word shows 40 characters for mail merge field result.

In this case, I suggest you please change the code of Name property of MergeField class as shown below. Hope this helps you. Please let us know if you have any more queries.

    // return ((FieldStart)mFieldStart).GetField().Result.Replace("«", "").Replace("»", "");
    string fieldcode = ((FieldStart)mFieldStart).GetField().GetFieldCode().Replace("MERGEFIELD", "").Trim();
    fieldcode = fieldcode.Substring(0, fieldcode.IndexOf(" ")).Trim();
    return fieldcode;

Thanks a lot for that. It did the trick. Not all my fieldcodes have a space in them for some reason so I added an IF around the second statement.

if (fieldcode.Contains(" "))
    fieldcode = fieldcode.Substring(0, fieldcode.IndexOf(" ")).Trim();

Thanks again

Hi Scott,

Thanks for your feedback. Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.