How to load metadata to SharePoint library along with file using ASP.NET web form

Galey, Jason 21 Reputation points
2022-12-14T18:05:52.01+00:00

I have the following code for uploading to a SharePoint Online document library, which is working. I can upload a file.

However, I'm having trouble adding the ability to also send metadata with the file. I'd like to add one or more columns of metadata with the upload. I've tried integrating some samples I've found without success.

If it's best to start over, I will. I just hate to tear down a working example if I don't need to.

Thanks!

Default.aspx:

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">  
  
    <div class="jumbotron">  
    </div>  
  
    <div class="row">  
        <div class="col-md-4">  
            <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>  
        </div>  
        <div class="col-md-4">  
        </div>  
        <div class="col-md-4">  
        </div>  
    </div>  
    <div>  
        <p></p>  
        <table>  
            <tr>  
                <td>SharePoint URL:</td>  
                <td><asp:TextBox ID="txtSharePointURL" runat="server" Width="345px">sharepoint site URL here</asp:TextBox></td>  
            </tr>  
            <tr>  
                <td>Library Name:</td>  
                <td><asp:TextBox ID="txtLibraryName" runat="server">Library Name Here</asp:TextBox></td>  
            </tr>  
            <tr>  
                <td>DBUID:</td>  
                <td><asp:TextBox ID="TextBox2" runat="server">1001</asp:TextBox></td>  
            </tr>  
            <tr>  
                <td>File:</td>  
                <td><asp:FileUpload ID="FileUpload1" runat="server"/></td>  
            </tr>  
            <tr>  
                <td></td>  
                <td><asp:Button ID="btnUpload" runat="server" Text="Button" OnClick="btnUpload_Click" /></td>  
            </tr>  
        </table>  
    </div>  
  
</asp:Content>  

Code Behind for this page:

using Microsoft.SharePoint.Client;  
using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Security;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
  
namespace SPDocLoadTEst  
{  
    public partial class _Default : Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
  
        }  
  
        public ClientContext SPClientContext { get; set; }  
        public Web SPWeb { get; set; }  
        public string SPErrorMsg { get; set; }  
  
        protected void btnUpload_Click(object sender, EventArgs e)  
        {  
            string sURL = txtSharePointURL.Text;  
            string sDocName = string.Empty;  
            if (!string.IsNullOrWhiteSpace(sURL) && !string.IsNullOrWhiteSpace(txtLibraryName.Text) && (this.FileUpload1.HasFile))  
            {  
                bool bbConnected = Connect(sURL, "user name here", "pwd here");  
                if (bbConnected)  
                {  
                    Uri uri = new Uri(sURL);  
                    string sSPSiteRelativeURL = uri.AbsolutePath;  
                    sDocName = UploadFile(FileUpload1.FileContent, FileUpload1.FileName, sSPSiteRelativeURL, txtLibraryName.Text);  
                    if (!string.IsNullOrWhiteSpace(sDocName))  
                    {  
                        lblMsg.Text = "The document " + sDocName + " has been uploaded successfully..";  
                    }  
                    else  
                    {  
                        lblMsg.Text = SPErrorMsg;  
                    }  
  
                }  
  
            }  
        }  
  
        public bool Connect(string SPURL, string SPUserLogin, string SPPassWord)  
        {  
            bool bConnected = false;  
            try  
            {  
                SPClientContext = new ClientContext(SPURL);  
                var securePassword = new SecureString();  
                foreach (char c in SPPassWord.ToCharArray()) securePassword.AppendChar(c);  
                SPClientContext.Credentials = new SharePointOnlineCredentials(SPUserLogin, securePassword);  
                SPWeb = SPClientContext.Web;  
                SPClientContext.Load(SPWeb);  
                SPClientContext.ExecuteQuery();  
                bConnected = true;  
            }  
            catch (Exception ex)  
            {  
                bConnected = false;  
                SPErrorMsg = ex.Message;  
            }  
            return bConnected;  
        }  
        public string UploadFile(Stream fs, string sFileName, string sSPSiteRelativeURL, string sLibraryName)  
        {  
            string sDocName = string.Empty;  
            try  
            {  
                if (SPWeb != null)  
                {  
                    var sFileUrl = String.Format("{0}/{1}/{2}", sSPSiteRelativeURL, sLibraryName, sFileName);  
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPClientContext, sFileUrl, fs, true);  
                    sDocName = sFileName;  
                }  
            }  
            catch (Exception ex)  
            {  
                sDocName = string.Empty;  
                SPErrorMsg = ex.Message;  
            }  
            return sDocName;  
        }  
    }  
  
}  
Microsoft 365 and Office | SharePoint | Development
Microsoft 365 and Office | SharePoint | For business | Windows
Developer technologies | ASP.NET | Other
{count} votes

Answer accepted by question author
  1. RaytheonXie_MSFT 40,496 Reputation points Microsoft External Staff
    2022-12-15T07:42:29.857+00:00

    Hi @Galey, Jason
    I will recommend you to upload files first. Then you can use csom to update the metadata. Please refer to following code

                    ClientContext context = new ClientContext("http://Sharepointsite");///SitePages/Home.aspx");  
                    System.Net.ICredentials creds = System.Net.CredentialCache.DefaultCredentials;  
      
                    context.Credentials = creds;  
                    context.RequestTimeout = 60000000; // Time in milliseconds  
      
                    string url = "/Members/";  
                    string fileName = Path.GetFileName(fn);                     
      
                    string fnUrl = url + fn;  
      
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fnUrl, fs, true);  
      
                    string uniqueRefNo = GetNextDocRefNo();  
      
                    SP.Web web = context.Web;  
      
                    Microsoft.SharePoint.Client.File newFile = web.GetFileByServerRelativeUrl(fnUrl);  
                    context.Load(newFile);  
                    context.ExecuteQuery();  
      
                    Web site = context.Web;  
                    List docList = site.Lists.GetByTitle("Members");  
      
                    context.Load(docList);  
                    context.ExecuteQuery();  
      
      
                    context.Load(docList.Fields.GetByTitle("Workflow Number"));  
                    context.Load(docList.Fields.GetByTitle("Agreement Number"));  
                    context.Load(docList.Fields.GetByTitle("First Name"));  
                    context.Load(docList.Fields.GetByTitle("Surname"));  
                    context.Load(docList.Fields.GetByTitle("ID Number"));  
                    context.Load(docList.Fields.GetByTitle("Date of Birth"));  
                    context.Load(docList.Fields.GetByTitle("Country"));  
                    context.Load(docList.Fields.GetByTitle("Document Description"));  
                    context.Load(docList.Fields.GetByTitle("Document Type"));  
                    context.Load(docList.Fields.GetByTitle("Document Group"));  
      
                    context.ExecuteQuery();                                  
      
    *********NEED TO GET THE INTERNAL COLUMN NAMES FROM SHAREPOINT************  
                    var name = docList.Fields.GetByTitle("Workflow Number").InternalName;  
                    var name2 = docList.Fields.GetByTitle("Agreement Number").InternalName;  
                    var name3 = docList.Fields.GetByTitle("First Name").InternalName;  
                    var name4 = docList.Fields.GetByTitle("Surname").InternalName;  
                    var name5 = docList.Fields.GetByTitle("ID Number").InternalName;  
                    var name6 = docList.Fields.GetByTitle("Date of Birth").InternalName;  
                    var name7 = docList.Fields.GetByTitle("Country").InternalName;  
                    var name8 = docList.Fields.GetByTitle("Document Description").InternalName;  
                    var name9 = docList.Fields.GetByTitle("Document Type").InternalName;  
                    var name10 = docList.Fields.GetByTitle("Document Group").InternalName;  
                    var name11 = docList.Fields.GetByTitle("Unique Document Ref No").InternalName;       
      
    **********NOW SAVE THE METADATA TO SHAREPOINT**********  
                    newFile.ListItemAllFields[name] = "927015";  
                    newFile.ListItemAllFields[name2] = "1234565";  
                    newFile.ListItemAllFields[name3] = "Joe";  
                    newFile.ListItemAllFields[name4] = "Soap";  
                    newFile.ListItemAllFields[name5] = "7502015147852";  
                    newFile.ListItemAllFields[name6] = "1975-02-01";  
                    newFile.ListItemAllFields[name7] = "ZA";  
                    newFile.ListItemAllFields[name8] = "Test";  
                    newFile.ListItemAllFields[name9] = "Requirements";  
                    newFile.ListItemAllFields[name10] = "Requirements";  
                    newFile.ListItemAllFields[name11] = uniqueRefNo;  
      
                    newFile.ListItemAllFields.Update();  
                    context.Load(newFile);  
                    context.ExecuteQuery();  
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Galey, Jason 21 Reputation points
    2022-12-16T14:47:28.397+00:00

    Thank you, this is very helpful.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.