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

Add Field Codes to INCLUDEIMAGE field


We need to set the "Data not stored with document" flag ("\d") when adding a Field to an existing Word document via Interop but can't figure how to do so.

This example works well in terms of inserting the image link but it stores the image within the document and not remotely (which we need).

            if (doc.Bookmarks.Exists("TrackingPixel"))
            {
                object oBookMark = "TrackingPixel";
                object newText = @"https://www.remotelocation.com/trackingpixel/secretcode";

                Range rng = doc.Bookmarks.get_Item(ref oBookMark).Range;
                rng.Select();

                rng.Fields.Add(
                    Range: rng,
                    Type: WdFieldType.wdFieldIncludePicture,
                    Text: newText,
                    PreserveFormatting: true
                    );

            }

Any held would be appreciated. Thanks.


Solution

  • There are a number of ways adding switches to field codes can be done.

    In the case presented in the question, the switch can be added to the string passed to the Textparameter:

        if (doc.Bookmarks.Exists("TrackingPixel"))
        {
            string fieldSwitches = " \d";
            object oBookMark = "TrackingPixel";
            object newText = @"https://www.remotelocation.com/trackingpixel/secretcode" + fieldSwitches;
    
            Range rng = doc.Bookmarks.get_Item(ref oBookMark).Range;
            // There's usually no need to select the Range unless the user should work with it
            //rng.Select();
    
            rng.Fields.Add(
                Range: rng,
                Type: WdFieldType.wdFieldIncludePicture,
                Text: newText,
                PreserveFormatting: true
                );
        }
    

    If this were an existing field code (the switch should be added after the fact) it's possible to assign new content to the string. For example:

    string fldCode = field.Code.Text;
    fldCode += " \d";
    field.Code.Text = fldCode;
    field.Update();
    

    FWIW when adding a field I often pass the entire field code in as a string (use only the Text parameter) and leave out the Type parameter. I'll also set PreserveFormatting to false unless I know I explicitly want that behavior. The first is a personal preference. For the second, the \* MergeFormat switch can result in very odd behavior when a field code updates with other (formatted, string) content. I will use it, however, for linked tables.