Question

I need to add a new document link to a document library using the client object model. I suspect I could copy the format of the .aspx file used in the "link to a document" items and upload it as a normal file but I'm hoping there is a neater way.

So what I want to do is the same as the code sample below but instead of creating a new document I want to create a new link to a document.

ClientContext context = new ClientContext("http://wdev2008:22880");
context.Load(context.Web);
List list = context.Web.Lists.GetByTitle("Test Doc Link Library");
context.Load(list);
context.ExecuteQuery();

FileCreationInformation fileCreateInfo = new FileCreationInformation();
fileCreateInfo.Content = new byte[] { 0x33 };
fileCreateInfo.Url = "zerobyte";
File file = list.RootFolder.Files.Add(fileCreateInfo);
context.Load(file);
context.ExecuteQuery();

Update: According to the mod on this forum I'm not allowed to ask how to do this with a web service in a separate question so I'll change the title, tags and content on this question. Does anyone know how to do the insert with a SharePoint web service or server side control or anything else?

Was it helpful?

Solution

Turns out it can be done but it's a bit of a hack that involves taking a copy of the .aspx file SharePoint uses for document links and doing a string search and replace on it Creating a 'Link to a Document' Item in a SharePoint Document Library programmatically.

I tailored the example to use the client object model:

 string docLinkTemplate = null;
 using (System.IO.StreamReader sr = new System.IO.StreamReader("SharePointDocLinkTemplate.txt"))
 {
     docLinkTemplate = sr.ReadToEnd();
 }

 string docLink = "http://myserver/test.doc";
 docLinkTemplate = String.Format(docLinkTemplate, docLink);

 FileCreationInformation fileCreateInfo = new FileCreationInformation();
 fileCreateInfo.Content = Encoding.UTF8.GetBytes(docLinkTemplate);
 fileCreateInfo.Url = "testlinkfordoc.doc.aspx";
 File file = list.RootFolder.Files.Add(fileCreateInfo);
 ListItem fileListItem = file.ListItemAllFields;
 fileListItem["ContentType"] = "Link to a Document";
 FieldUrlValue urlValue = new FieldUrlValue();
 urlValue.Description = "Link to doc test";
 urlValue.Url = docLink;
 fileListItem["URL"] = urlValue;
 context.Load(file);
 context.ExecuteQuery();

(Hopefully the mod won't deem this answer unworthy again. Pity the mods on these programming web sites don't have to get stackoverflow rep before they can start throwing their weight around.)

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top