0

I am new to SharePoint Development, I am facing issue in importing the data to SPonline list. I am trying to import CSV data to a SharePoint Online custom list using client ID and Client Secret. I have written the below C# code to run in console application. But i am not getting the expected output(import data to list). Your help is appreciated!!!

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="Sites"
             type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  <system.net>
    <defaultProxy useDefaultCredentials="true"> </defaultProxy>
  </system.net>
  <Sites>
    <add key="site2"
         value="https://******.sharepoint.com"/>
  </Sites>
  <appSettings>
    <add key="ClientId" value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>
    <add key="ClientSecret" value="yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"/>
  </appSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Reflection;
using System.Security;
using Microsoft.SharePoint;
using System.IO;
using System.Configuration;
using System.Collections.Specialized;
using System.Runtime;

namespace TestConsole
{
    class Program
    {
                static void Main(string[] args)
                {

                    var config = (NameValueCollection)ConfigurationManager.GetSection("Sites");
                    foreach (var key in config.Keys)
                    {

                         Uri siteUri = new Uri(config.GetValues(key as string)[0]);
                         //Get the realm for the URL
                         string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);

                //Get the access token for the URL.  
                //   Requires this app to be registered with the tenant
                string accessToken = TokenHelper.GetAppOnlyAccessToken(
                    TokenHelper.SharePointPrincipal, 
                    siteUri.Authority, realm).AccessToken;

                //Get client context with access token
                using(var clientContext = 
                    TokenHelper.GetClientContextWithAccessToken(
                        siteUri.ToString(),accessToken))
            {
                const string filePath = @"D:\import.csv";
                StreamReader streamreader = new StreamReader(filePath);
                string[] totalData = new string[System.IO.File.ReadAllLines(filePath).Length];
                totalData = streamreader.ReadLine().Split('|');
                string strTitle;
                string strSurname = string.Empty;
                using (var context = new ClientContext(siteUri.ToString()))
                    {
                        Web currentWeb = clientContext.Web;
                        clientContext.Load(currentWeb);

                    while (!streamreader.EndOfStream)
                    {
                        totalData = streamreader.ReadLine().Split('|');
                        strTitle = totalData[1];
                        strSurname = totalData[0];
                        if (totalData.Length > 2)
                        {
                            strSurname = totalData[2];
                        }
                        List spList = context.Web.Lists.GetByTitle("CSVList");
                        ListItemCreationInformation creationInfo = new ListItemCreationInformation();
                        ListItem oListItem = spList.AddItem(creationInfo);
                        oListItem["Title"] = strTitle;
                        oListItem["Surname"] = strSurname;
                        oListItem.Update();
                        clientContext.ExecuteQuery();

                    }
                }
            }


           }
                Console.WriteLine("...");
                Console.ReadLine();

            }




        }
    }
0

I have changed the code and you can update accordingly to your logic.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using System.Web;
using System.Net;
using System.Configuration;
using System.Collections.Specialized;
using Microsoft.SharePoint.Client;
using System.Runtime;
using Microsoft.SharePoint;
using System.Reflection;



namespace ConsoleApplication3
{

    class Program
    {
        static void Main(string[] args)
        {
            try
            {


                var configSites = (NameValueCollection)ConfigurationManager.GetSection("Sites");
                foreach (var key in configSites.Keys)
                {
                    Uri siteUri = new Uri(configSites.GetValues(key as string)[0]);
                    var siteUrls = configSites.GetValues(key as string);
                    var context = new ClientContext(siteUri.ToString());
                    if (siteUrls != null)
                    {
                        string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);

                        string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken;





                        using (var clientContext = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken))
                        {

                            const string filePath = @"Your .CSV Path";
                            StreamReader streamReader = new StreamReader(filePath);
                            while (!streamReader.EndOfStream)
                            {

                                string[] totalData = new string[System.IO.File.ReadAllLines(filePath).Length];
                                string strName = string.Empty;
                                string strPartNumber = string.Empty;
                                string strSurName = string.Empty;
                                DateTime dtToday = DateTime.Now;


                                if (streamReader != null)
                                {
                                    Console.Write("while reading");

                                    totalData = streamReader.ReadLine().Split('|');

                                    if (totalData.Length > 1)
                                    {
                                        strName = totalData[1];
                                    }
                                    if (totalData.Length > 2)
                                    {
                                        strSurName = totalData[2];
                                    }

                                    if (totalData.Length > 5)
                                    {
                                        strPartNumber = totalData[5];
                                    }
                                    List spList = clientContext.Web.Lists.GetByTitle("Your Custom List Name");

                                    ListItemCreationInformation creationInfo = new ListItemCreationInformation();
                                    ListItem oListItem = spList.AddItem(creationInfo);
                                    oListItem["Name"] = strName;
                                    oListItem["Title"] = strSurName;
                                    oListItem["Surname"] = strSurName;
                                    oListItem["BirthDate"] = dtToday;
                                    oListItem.Update();
                                    clientContext.ExecuteQuery();
                                }

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }


        }
    }
}

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.