How to use CSOM to copy file into Office 365

For last few weeks I have to make integration between SharePoint online (Office 365) and local system for one of my clients, and in my case I have to use CSOM to copy file into SharePoint online (Office 365). Of course it’s different when you make integration between systems which belongs to you, and you have to use different approach when you have to connect  to Office 365. In this case everything has been configured by Microsoft and you have to use what has been exposed to you. Right now, we have to possible option to use:

– REST – Representational State Transfer
– CSOM – Client side Object Model

You will find many examples of CSOM on MSDN. Right now I just show you only copy operation between your environment and Office 365 (SharePoint online).  Below you will find code example, which has been used to download the file from SharePoint online (uoload method is almost the same):

 static void Main(string[] args)
        {
            const string userName = "[email protected]";
            const string password = "yourpassword"; 

            const string url = "https://company.sharepoint.com/sites/SiteCollection/Files/MyFile.xlsx";

            string dest = @"D:\abc\" + "Myfile.xlsx";

            var encryptedPassword = new SecureString();
            foreach (var c in password.ToCharArray()) encryptedPassword.AppendChar(c);
            var credentials = new SharePointOnlineCredentials(userName, encryptedPassword);

            downloadTheFile(url, credentials, dest);

        }

        private static void downloadTheFile(string siteURL, ICredentials credentials, string fileRelativeUrl)
        {
            using (var webClient = new WebClient())
            {
                webClient.Credentials = credentials;
                webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                webClient.DownloadFile(siteURL, fileRelativeUrl);
            }

        }

Just a few words for the code above. Before you run any operation you have to authenticate against Office 365. To do this we have to use the class SharePointOnlineCredentials, which can grant us access to the Microsoft cloud. After that, we can use some methods which are accessible with WebClient. In my case I used DownloadFile, but there’s also UploadFile, which can be used to upload files on the server. As you can see the code is very simple and CSOM usage makes it available to run even with a simple console application.