Share SharePoint document programmatically | CloudFronts

Share SharePoint document programmatically

Introduction:

Sometimes it is required to share the certain documents with outside users. It is possible that user can share that document as hard copy. If that document is hosted on SharePoint user can make a shareable link.

Description:

Sharing a document to the outside users are possible via directly going to SharePoint and creating a shareable link. But what if you want to generate a shareable link using the C# code.

You can follow below code to generate shareable link in Online SharePoint.

1. Get the link
You need to pass the document link to below function as shown.

currentLink = https://organization.sharepoint.com/cf_car/JTN_89330b3c-beb5-e811-a968-000d3a324f4c/Untitled2.png

2. Get the base url of your SharePoint and generate the service context

using (var context = new ClientContext(Model.SharePointBaseURL)){}

3. Authenticate the user

foreach (var c in Model.AdminPassword) passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials(Model.AdminUserName, passWord);

4. CreateAnonymousLink method which will generate the shareable link

var orgEditLink = Web.CreateAnonymousLink(context, currentLink, true);

5. Execute the query

context.ExecuteQuery();

6. Finally get the public link

editUrl = orgEditLink.Value;

Complete code:

        private static string UpdateLinkTOShareable(string currentLink, Entity document)
        {
            string editUrl = string.Empty;

            using (var context = new ClientContext(Model.SharePointBaseURL))
            {
                var passWord = new SecureString();
                foreach (var c in Model.AdminPassword) passWord.AppendChar(c);
                context.Credentials = new SharePointOnlineCredentials(Model.AdminUserName, passWord);
                try
                {
                    var orgEditLink = Web.CreateAnonymousLink(context, currentLink, true);
                    context.ExecuteQuery();
                    editUrl = orgEditLink.Value;

                }
                catch (Exception ex)
                {

                }
                /*Code to make link Public End*/


                return editUrl;
            }
        }
 

Share Story :

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close