I want to programmatically (c# csom) create anonymous view links to SharePoint online documents to enable guest users to View the documents without requiring them to sign in. After extensive research, I found these two snippets code.

This supposedly creates the link:

var newRoleAssignment = new UserRoleAssignment() { Role = Role.View, UserId = "" };

                                new List<UserRoleAssignment>() { newRoleAssignment },
                                validateExistingPermissions: true,
                                additiveMode: true,
                                sendServerManagedNotification: true,
                                customMessage: null,
                                includeAnonymousLinksInNotification: true);

And this, retrieves the link from the document:

var objSharingInfo = ObjectSharingInformation.GetObjectSharingInformation(
                            ctx, item, false, true, false, true, true, true, true);
                    orderDets = objSharingInfo.AnonymousViewLink;

The problem with the first snippet is that I don't know which UserID to pass. I tried with an empty string and with my account's ID and in both cases when loading the objSharingInfo (in the second snippet) I am getting an Exception with a message of "Unknown Error".

When I load the objSharingInfo on other items, independently to Snippet 1, on documents whose guest link would already have been manually created from SharePoint: Snippet 2 works and I can extract the link from objSharingInfo.

Any help would be appreciated - or else maybe there are any other ways to achieve this?


To generate the anonymous link, you can use the below code:

string link = context.Web.CreateAnonymousLinkForDocument("https://tenantname.sharepoint.com/Documents/sample.docx",ExternalSharingDocumentOption.View);

To share the document, you can use the below code:

SharingResult result = context.Web.ShareDocument("https://tenantname.sharepoint.com/Documents/sample.docx", "someone@example.com", ExternalSharingDocumentOption.View,true, "Doc shared programmatically");

External sharing API for SharePoint and OneDrive for Business

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.