Uploading a file into a library via CSOM, even if the library does not exist

A customer of mine asked me how to upload a file, using CSOM from .NET, into a target library/folder regardless the target folder already exists or not.

Here you can see a code sample, which leverages the ExceptionHandlingScope available in CSOM.

static void FileUploadWithExceptionHandlingScope()
ClientContext ctx = new ClientContext(“http://demo-sp2013.sharepoint.local/sites/DemoSite/“);
ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);
using (scope.StartScope())
using (scope.StartTry())
// Try to reference the target folder
Folder folder = ctx.Web.GetFolderByServerRelativeUrl(“TargetFolder”);
using (scope.StartCatch())
// Create the library, in case it doesn’t exist
ListCreationInformation lci = new ListCreationInformation();
lci.Title = “TargetFolder”;
lci.Description = “TargetFolder”;
lci.TemplateType = (Int32)ListTemplateType.DocumentLibrary;
lci.QuickLaunchOption = QuickLaunchOptions.On;
List library = ctx.Web.Lists.Add(lci);
using (scope.StartFinally())
// Add the ListItem, whether the list has just been created
// or was already existing
Folder folder = ctx.Web.GetFolderByServerRelativeUrl(“TargetFolder”);
FileCreationInformation fci = new FileCreationInformation();
fci.Content = System.IO.File.ReadAllBytes(@”..\..\SampleFile.txt”);
fci.Url = “SampleFile.txt”;
fci.Overwrite = true;
File fileToUpload = folder.Files.Add(fci);
// Now invoke the server, just one time

The sample above works either in SharePoint 2010 or in SharePoint 2013.