At the moment I'm working with Word.dotx files that hold several bookmarks which are being altered by a c# program.
For a Rebranding project I need to add several new bookmark fields and my predecessor code does reference to the Text Form Field Legacy Control inside Office Word 2010.
I create a new Text Form Field with Field Settings Bookmark pointed to TestBookmark1. I'm already aware of a certain bug that the bookmarkname of a text form field can contain max 20 chars.
When I run the testcode, the existing bookmarks are replaced perfectly while it crashes on the new bookmarks. The exception I receive here is "The range cannot be deleted"
The code that is used for replacing the bookmark goes as follows:
public void ReplaceBookmark(string bookmarkName, string text)
{
try
{
var bookmarks = GetProperty("Bookmarks", _wordDoc); //worddoc is the Word.Document equivalent in late binding
var exists = InvokeMember("Exists",
bookmarks,
new object[]
{
bookmarkName
}) != null && (bool)InvokeMember("Exists",
bookmarks,
new object[]
{
bookmarkName
});
if (!exists)
return;
var bookmark = InvokeMember("Item",
bookmarks,
new object[]
{
bookmarkName
});
var range = GetProperty("Range", bookmark);
SetProperty("Text", range, text);
InvokeMember("Add",
bookmarks,
new[]
{
bookmarkName, range
});
}
catch
{
CloseWord(false);
throw;
}
}
The exception get's thrown at SetProperty("Text", range, text);
private static void SetProperty(string propertyName, object instance, object value)
{
if (instance == null)
return;
var type = instance.GetType();
type.InvokeMember(propertyName,
BindingFlags.SetProperty,
null,
instance,
new[]
{
value
});
}
When going deeper here it falls on the type.InvokeMember function.
I already saw a likewise solution found Here, But this example uses the Early binding principle that I for company reasons cannot use.
This leaves me with the following questions:
- Am i adding the bookmarks incorrectly, or am i simply forgetting something?
- Why do i get the "Range cannot be Deleted Exception"?
- When i catch this specific error, is there another way to replace the bookmark?
Thanks in advance