Loop through all Hyperlinks within document

Hi alexey noskov,
Do you have the Code for C#?
I need to find all Hyperlinks from Document and display the links in a form
Thanks

@omar.sidiqy Sure, you can use code like this to loop through all hyperlinks in the document in C#:

Document doc = new Document("in.docx");

// Get all hyperlinks in the document.
List<FieldHyperlink> hyperlinks = doc.Range.Fields
    .Where(f => f.Type == FieldType.FieldHyperlink).Cast<FieldHyperlink>().ToList();

// loop through all hyperlinks
foreach (FieldHyperlink hyperlink in hyperlinks)
{
    Console.WriteLine(hyperlink.Address);
}

Hi alexey Noskov,
Thank you so much for your quick response, but it’s working fine for links like :
https://docs.aspose.com/words/net/working-with-hyperlinks/
but I linked a shape in a word document with a specific sheet and a range of an excel file, when I am opening the word to see the link I have to press Alt+F9 to see that and the link looks like this:
{LINK Excel.SheetMacroEnabled.12 \\\servername\ADrive\Report\\charts_template.xlsm!Sheetname!R1C7:R37C19\a\p}
so I need to read this type of link, I mean getting the link of a table or shape in word with an excel file
Thanks in advance

@omar.sidiqy This is not hyperlink, this is a LINK field. In this case you should use FieldType.FieldLink and FieldLink appropriately.

@alexey.noskov, Can you write a sample code on how to use that?

@omar.sidiqy Sure, the code is pretty much similar to the code I have provided earlier:

Document doc = new Document("in.docx");

// Get all LINK fields in the document.
List<FieldLink> links = doc.Range.Fields
    .Where(f => f.Type == FieldType.FieldLink).Cast<FieldLink>().ToList();

// loop through all links
foreach (FieldLink link in links)
{
    Console.WriteLine(link.SourceFullName);
}

@alexey.noskov, unfortunately still it’s not working for that type of link.
the “doc.Range.Fields” is empty, although it has the link, I don’t know why.

@omar.sidiqy Could you please attach your document here for testing? We will check the issue and provide you more information.

@alexey.noskov Sure, here is the file.
SampleFile.docx (21.9 KB)

@omar.sidiqy The object you would like to get is a linked OLE object. It is represented as Shape in Aspose.Words DOM. So you can use code like this to get such objects in your document:

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

List<Shape> oleObjects = doc.GetChildNodes(NodeType.Shape, true)
    .Cast<Shape>().Where(s => (s.OleFormat != null) && s.OleFormat.IsLink).ToList();

foreach (Shape s in oleObjects)
    Console.WriteLine(s.OleFormat.SourceFullName);

@alexey.noskov, Thank you so much, appreciate it. its working now

1 Like