0

Everything else works perfectly. Why am I getting an access denied when trying to execute this code ?

            string password = "password";
            var securePassword = new System.Security.SecureString();

  
            Uri siteUri = new Uri("https://contoso.sharepoint.com/sites/xxx/");
            string user = "user@domain.onmicrosoft.com";
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            using (var authenticationManager = new AuthenticationManager())
            using (var context = authenticationManager.GetContext(siteUri, user, securePassword))
            {
                context.Load(context.Web, p => p.Title);
                context.ExecuteQuery();
                Console.WriteLine($"Title: {context.Web.Title}");

                // Load Site
                Site site = context.Site;
                context.Load(site);
                context.ExecuteQuery();

                // Load RootWeb
                Web rootWeb = site.RootWeb;
                context.Load(rootWeb);
                context.ExecuteQuery();

                // Get or create site (if it does not exist)
                context.Load(rootWeb.Webs);
                context.ExecuteQuery();
                Web web = rootWeb.Webs.SingleOrDefault(w => w.Title.Equals("new web", StringComparison.OrdinalIgnoreCase));

                if (web == null)
                {
                    // SharePoint target site not found, we need to create it
                    WebTemplate webTemplate = null;
                    
                    // Create site
                    WebCreationInformation webCreationInformation = new WebCreationInformation()
                    {
                        Description = "2052",
                        Language = Convert.ToInt32(rootWeb.Language), 
                        Title = "2052",
                        Url = "2052",
                        UseSamePermissionsAsParentSite = true,
                        WebTemplate = webTemplate != null ? webTemplate.Name : "STS#0"
                    };
                    web = rootWeb.Webs.Add(webCreationInformation);
                }
                context.Load(web, w => w.Title);
                context.ExecuteQuery();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.