不幸的是,您无法使用 OpenXml 直接更改超链接路径。唯一的方法是找到当前超链接的 HyperlinkRelation 对象并将其替换为具有相同关系 Id 但新超链接路径的 hew 对象:
using DocumentFormat.OpenXml.Wordprocessing;
MainDocumentPart mainPart = doc.MainDocumentPart;
Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault();
if (hLink != null)
{
// get hyperlink's relation Id (where path stores)
string relationId = hLink.Id;
if (relationId != string.Empty)
{
// get current relation
HyperlinkRelationship hr = mainPart.HyperlinkRelationships.Where(a => a.Id == relationId).FirstOrDefault();
if (hr != null)
// remove current relation
{ mainPart.DeleteReferenceRelationship(hr); }
//add new relation with same Id , but new path
mainPart.AddHyperlinkRelationship(new System.Uri(@"D:\work\DOCS\new\My.docx", System.UriKind.Absolute), true, relationId);
}
}
// apply changes
doc.Close();