Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: доступ запрещен - PullRequest
0 голосов
/ 15 октября 2019

Я обнаружил исключение, когда использовал код c # для создания подкаталогов в указанном каталоге sharepoint.

Сообщение об исключении: Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: доступ запрещен. У вас нет разрешения на выполнение этого действия или доступ к этому ресурсу.

Кто-нибудь может мне помочь? спасибо!

Ниже приведены параметры:

  • file: D: \ Repos \ helpfilesync \ ArtefactUploader \ bin \ Release \ ArtefactUploader.exe
  • fileName: ArtefactUploader. exe
  • uploadPath: / sites / Platform / Общие документы / dailybuild / helpfilesync /
  • subFolderPath: v0.1.0 /

    public void Upload()
    {
        using (ClientContext clientContext = new ClientContext("*****"))
        {
            SecureString pass = new SecureString();
            foreach (char ch in password)
            {
                pass.AppendChar(ch);
            }
            clientContext.Credentials = new SharePointOnlineCredentials(user, pass);
            Web web = clientContext.Web;
            clientContext.Load(web);
            clientContext.ExecuteQuery();
    
            if (!string.IsNullOrWhiteSpace(this.subFolderPath))
            {
                CreateFolder(clientContext.Web, uploadPath, subFolderPath);
            }
    
            using (FileStream fs = new FileStream(file, FileMode.Open))
            {
                Microsoft.SharePoint.Client.File.SaveBinaryDirect
                    (clientContext, $"{this.uploadPath}{this.subFolderPath}/{fileName}", fs, true);
            }
    
            Console.WriteLine("Uploaded File Successfully");
        }
    }
    
    public void CreateFolder(Web web, string relativePath, string fullFolderPath)
    {
        if (web == null)
        {
            throw new ArgumentNullException(nameof(web));
        }
    
        if (string.IsNullOrWhiteSpace(relativePath))
        {
            throw new ArgumentNullException(nameof(relativePath));
        }
    
        if (string.IsNullOrWhiteSpace(fullFolderPath))
        {
            throw new ArgumentNullException(fullFolderPath);
        }
    
        Folder relativeFolder = web.GetFolderByServerRelativeUrl(relativePath);
        CreateFolderInternal(web, relativeFolder, fullFolderPath);
    }
    
    public static Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderPath)
    {
        var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
        string folderUrl = folderUrls[0];
        var curFolder = parentFolder.Folders.Add(folderUrl);
        //web.Context.Load(curFolder);
        try
        {
            web.Context.ExecuteQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    
    
        if (folderUrls.Length > 1)
        {
            var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
            return CreateFolderInternal(web, curFolder, folderPath);
        }
    
        return curFolder;
    }
    

Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: доступ запрещен. У вас нет разрешения на выполнение этого действия или доступ к этому ресурсу. в Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream (Stream responseStream) в Microsoft.SharePoint.Client.ClientRequest.ProcessResponse () в Microsoft.SharePoint.Client.ClientContext.ExecuteQuery () в родительском элементе веб-сайта. , String fullFolderPath) в D: \ Repos \ helpfilesync \ ArtefactUploader \ SharepointUploader.cs: строка 96

1 Ответ

0 голосов
/ 16 октября 2019

Сделал тест вашего кода, отлично работает. Убедитесь, что имя пользователя / пароль верны.

class Program
    {

        const string user = "user@teanat.onmicrosoft.com";
        const string password = "password";
        public static void Upload()
        {
            using (ClientContext clientContext = new ClientContext("https://tenant.sharepoint.com/sites/lee"))
            {
                SecureString pass = new SecureString();
                foreach (char ch in password)
                {
                    pass.AppendChar(ch);
                }
                clientContext.Credentials = new SharePointOnlineCredentials(user, pass);
                Web web = clientContext.Web;
                clientContext.Load(web);
                clientContext.ExecuteQuery();

                if (!string.IsNullOrWhiteSpace("a"))
                {
                    CreateFolder(clientContext.Web, "/sites/lee/mydoc2", "childA");
                }

                //using (FileStream fs = new FileStream(file, FileMode.Open))
                //{
                //    Microsoft.SharePoint.Client.File.SaveBinaryDirect
                //        (clientContext, $"{this.uploadPath}{this.subFolderPath}/{fileName}", fs, true);
                //}

                Console.WriteLine("Uploaded File Successfully");
            }
        }

        public static void CreateFolder(Web web, string relativePath, string fullFolderPath)
        {
            if (web == null)
            {
                throw new ArgumentNullException(nameof(web));
            }

            if (string.IsNullOrWhiteSpace(relativePath))
            {
                throw new ArgumentNullException(nameof(relativePath));
            }

            if (string.IsNullOrWhiteSpace(fullFolderPath))
            {
                throw new ArgumentNullException(fullFolderPath);
            }

            Folder relativeFolder = web.GetFolderByServerRelativeUrl(relativePath);
            CreateFolderInternal(web, relativeFolder, fullFolderPath);
        }

        public static Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderPath)
        {
            var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string folderUrl = folderUrls[0];
            var curFolder = parentFolder.Folders.Add(folderUrl);
            //web.Context.Load(curFolder);
            try
            {
                web.Context.ExecuteQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }


            if (folderUrls.Length > 1)
            {
                var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
                return CreateFolderInternal(web, curFolder, folderPath);
            }

            return curFolder;
        }

        static void Main(string[] args)
        {
            Upload();
        }
    }

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...