3
votes

I want to upload a file from local directory to Share Point document library using SSIS. I am using Script Task to do so. While running the package I am getting below error:

The remote server returned an error: (403) Forbidden.

Script Task code is as below:

public void Main()
        {
            // TODO: Add your code here
            WebClient myWebClient;
            string DestinationURL;
            string LocalFileName;
            bool FireAgain = true;
            try
            {
                myWebClient = new WebClient();
                myWebClient.Headers.Add("user-agent", "Only a test!");
                LocalFileName = @"C:\Users\jay.desai\Desktop\LSRSQL01_ACXM_20201003.html";
                DestinationURL = @"https://companyname.sharepoint.com/sites/DataServices/Shared%20Documents/Data%20Dictionaries/LSRSQL01_ACXM_20201003.html";
                Console.WriteLine(LocalFileName);
                myWebClient.Credentials = new NetworkCredential("[email protected]", "HelloWorld@2891", "NATSYS");
                myWebClient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                //myWebClient.UseDefaultCredentials = true;
                Dts.Events.FireInformation(0, String.Empty, String.Format("Uploading {0} to {1}", LocalFileName, DestinationURL), String.Empty, 0, ref FireAgain);
                // upload the file
                myWebClient.UploadFile(DestinationURL, "PUT", LocalFileName);
            }
            catch (Exception ex)
            {
                // Catch and handle error
                Dts.Events.FireError(0, String.Empty, ex.Message, String.Empty, 0);
            }

            Dts.TaskResult = (int)ScriptResults.Success;
        }

I am able to open the same folder and upload the file using browser.

1

1 Answers

0
votes

It got resolved by using CSOM. For that first you need to install SharePoint Online Client Components SDK. Then in the project you have to reference Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime. Microsoft reference is here

Use below code in script task:

public void Main()
        {
            // TODO: Add your code here
            ClientContext clientContext = new ClientContext("https://companyname.sharepoint.com");

            SecureString passWord = new SecureString();
            foreach (char c in "HelloWorld@1234".ToCharArray()) passWord.AppendChar(c);
            clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);

            using(FileStream fileStream = new FileStream(@"C:\Users\jay.desai\Desktop\LSRSQL01_ACXM_20201003.html", FileMode.Open))
            ClientOM.File.SaveBinaryDirect(clientContext, "/sites/DataServices/Shared Documents/Data Dictionaries/LSRSQL01_ACXM_20201003.html", fileStream, true);

            Dts.TaskResult = (int)ScriptResults.Success;
         }