Search code examples
c#sharepointsharepoint-2010sharepoint-online

Get file url from sharepoint by name


I'm able to save document in Sharepoint documents. Once the document is saved I want to be able to get the url of that document so I can share the url with a user.

This is the code I'm using to save the document:

using (ClientContext clientContext = new ClientContext("https://mydomain.sharepoint.com"))
{
    SecureString passWord = new SecureString();
    foreach (char c in "mypassword".ToCharArray()) passWord.AppendChar(c);
    clientContext.Credentials = new SharePointOnlineCredentials("myaccount@mydomain.com", passWord);
    Web web = clientContext.Web;
    FileCreationInformation newFile = new FileCreationInformation();
    //newFile.Content = System.IO.File.ReadAllBytes(filePath);
    byte[] docData = null;
    byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        docData = ms.ToArray();
    }
    newFile.Content = docData;
    newFile.Url = originalFileName;

    List docs = web.Lists.GetByTitle("DOCUMENTS");
    Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
    clientContext.ExecuteQuery();
}

How I can get the URL of that document once it's uploaded?


Solution

  • You can use either of the below 3 methods. To share a document, you can generate anonymous link, anon link with expiration date or share and send it via email.

    List docs = web.Lists.GetByTitle("DOCUMENTS");
    Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
    clientContext.ExecuteQuery();
    
    clientContext.Load(uploadFile.ListItemAllFields, item => item["EncodedAbsUrl"]);
    clientContext.ExecuteQuery();
    
    var fileUrl = uploadFile.ListItemAllFields["EncodedAbsUrl"].ToString();
    
    string link = clientContext.Web.CreateAnonymousLinkForDocument(fileUrl, ExternalSharingDocumentOption.View);
    
    string linkwithExpiration = clientContext.Web.CreateAnonymousLinkWithExpirationForDocument(fileUrl, ExternalSharingDocumentOption.Edit, DateTime.Now.AddMonths(1));
    
    SharingResult result = clientContext.Web.ShareDocument(fileUrl, "someone@example.com", ExternalSharingDocumentOption.View, true, "Doc shared programmatically");
    

    Ensure that external sharing capability is turned on.

    Reference - Turn on external sharing in SPO