0

Unable to upload the documents in SharePoint Online using a console application. Any solution to this problem?

public static void SaveFileToSharePoint(string fileName)
    {

       string Url = "https://xxxxx.sharepoint.com/sites";
       string libraryName = "Shared Documents";

        using (ClientContext clientContext = new ClientContext(Url))
                        {
                            SecureString passWord = new SecureString();
                            foreach (char c in "*****".ToCharArray()) passWord.AppendChar(c);
                            clientContext.Credentials = new SharePointOnlineCredentials("[email protected]",
                                passWord);
                            List list = clientContext.Web.Lists.GetByTitle(libraryName);
                            clientContext.Load(list.RootFolder);
                            clientContext.ExecuteQuery();
                            using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
                            {
                                Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, list.RootFolder.ServerRelativeUrl.ToString() + "/" + fileName.Split('\\')[1], fileStream, true);
                            }
                        }

    }

1 Answer 1

2

You should refer this link once. This post contains the code for authenticating with your SharePoint Online and upload a file into the given library.

 class Program
    {
        static void Main(string[] args)
        {
            using (ClientContext clientContext = new ClientContext("https://xxxx.sharepoint.com/sites/SiteName"))
            {
                SecureString passWord = new SecureString();
                foreach (char c in "YourPassword".ToCharArray()) passWord.AppendChar(c);
                clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);
                Web web = clientContext.Web;
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content = System.IO.File.ReadAllBytes(@"C:\Applications\PropertyMaster.xlsx"); // this is my sample file path
                newFile.Url = "testFile.xlsx"; // file name which should be created in library

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

The above code worked for me.

My Output image

I have created a console application. Still you have any issue then inform me.

5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.