Проблема добавления / загрузки / обновления файла на сервере Sharepoint - PullRequest
0 голосов
/ 03 февраля 2020

Я использую приведенный ниже код для добавления локального файла на сервер sharepoint:

using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.SharePoint.Client;
using MSharp.Framework.Services;
using System;
using System.IO;
using System.Net;
using System.Security;

namespace SharepointFileSend
{
    class Program
    {
        private const string V = "XXXX!";
        private static string hostWeb="company.sharepoint.com";

        static void Main(string[] args)
        {
            string siteUrl = "https://company.sharepoint.com/site/";

            string password = "XXXX!";
            //Insert Credentials
            ClientContext context = new ClientContext(siteUrl);

            var securePassword = new SecureString();

            foreach (var c in password.ToCharArray() ) securePassword.AppendChar(c);
            context.Credentials = new SharePointOnlineCredentials("xyz@company.com", securePassword);
            Web site = context.Web;

            //Get the required RootFolder
            string barRootFolderRelativeUrl = "Documents/Global Procurement";
            Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);

            //Create new subFolder to load files into
            string newFolderName = "SPTest";
            barFolder.Folders.Add(newFolderName);
            barFolder.Update();

            //Add file to new Folder
            Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
            string sharePointDocPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "Sharepoint.xml");

            FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(sharePointDocPath), Url = Path.GetFileName(sharePointDocPath), Overwrite = true };
            currentRunFolder.Files.Add(newFile);
            currentRunFolder.Update();

            context.ExecuteQuery();

            //Return the URL of the new uploaded file
           // string newUrl = siteUrl + barRootFolderRelativeUrl + "/" + newFolderName + "/" + Path.GetFileName(@p);
        }
    }
}


But, i am getting below exception:

using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.SharePoint.Client;
using MSharp.Framework.Services;
using System;
using System.IO;
using System.Net;
using System.Security;

namespace SharepointFileSend
{
    class Program
    {
        private const string V = "PennyRoyal8696!";
        private static string hostWeb="company.sharepoint.com";

        static void Main(string[] args)
        {
            string siteUrl = "https://company.sharepoint.com/site/";

            string password = "PennyRoyal8696!";
            //Insert Credentials
            ClientContext context = new ClientContext(siteUrl);

            var securePassword = new SecureString();

            foreach (var c in password.ToCharArray() ) securePassword.AppendChar(c);
            context.Credentials = new SharePointOnlineCredentials("XXX@XXX.com", securePassword);
            Web site = context.Web;

            //Get the required RootFolder
            string barRootFolderRelativeUrl = "Documents/Global";
            Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);

            //Create new subFolder to load files into
            string newFolderName = "SPTest";
            barFolder.Folders.Add(newFolderName);
            barFolder.Update();

            //Add file to new Folder
            Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
            string sharePointDocPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "Sharepoint.xml");

            FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(sharePointDocPath), Url = Path.GetFileName(sharePointDocPath), Overwrite = true };
            currentRunFolder.Files.Add(newFile);
            currentRunFolder.Update();

            context.ExecuteQuery();

            //Return the URL of the new uploaded file
           // string newUrl = siteUrl + barRootFolderRelativeUrl + "/" + newFolderName + "/" + Path.GetFileName(@p);
        }
    }
}

в последней строке ExecuteQuery (); Я получил исключение ниже: System. Net .WebException: 'Удаленный сервер возвратил ошибку: (400) Bad Request.'

Пожалуйста, предложите мне улучшить код, чтобы избежать этого исключения, а также ввести c в обновить существующий файл в Sharepoint.

1 Ответ

0 голосов
/ 04 февраля 2020

Пример тестового кода для вашей справки.

string SiteURL = @"https://xxx.sharepoint.com/sites/lee/";

            var login = "user@xxx.onmicrosoft.com";
            var password = "Password";

            var securePassword = new SecureString();

            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

            using (var context = new ClientContext(SiteURL))
            {
                context.Credentials = onlineCredentials;
                Web site = context.Web;

                //Get the required RootFolder
                string barRootFolderRelativeUrl = "/sites/lee/LibDS/Folder";
                Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);

                //Create new subFolder to load files into
                string newFolderName = "SPTest";
                barFolder.Folders.Add(newFolderName);
                //barFolder.Update();
                context.ExecuteQuery();

                //Add file to new Folder
                Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
                string sharePointDocPath = @"C:\Lee\test.docx";//System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "Sharepoint.xml");

                FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(sharePointDocPath), Url = Path.GetFileName(sharePointDocPath), Overwrite = true };
                var uploadedFile=currentRunFolder.Files.Add(newFile);
                //currentRunFolder.Update();
                context.Load(uploadedFile);
                context.ExecuteQuery();

                //update
                var item = uploadedFile.ListItemAllFields;
                item["Title"] = "Updated Title";
                item.Update();
                context.ExecuteQuery();
                Console.WriteLine("---------");
            }
...