Как добавить контент в файл sharepoint, используя C# api - PullRequest
1 голос
/ 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 = "XXXXX";
        private static string hostWeb="XXXXX.sharepoint.com";

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

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

            var securePassword = new SecureString();

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

            //Get the required RootFolder
            string barRootFolderRelativeUrl = "Documents/Demo";
            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);
        }
    }
}

Я получаю исключение при последнем утверждении:

context.ExecuteQuery ();

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

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

1 Ответ

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

Если вы используете библиотеку «Documents» по умолчанию, относительный URL-адрес папки root библиотеки в вашем коде будет « Shared% 20Documents / Demo ». И проверьте правильность URL-адреса сайта.

Следующий пример кода для справки.

string siteUrl = "https://tenant.sharepoint.com/sites/team";
string userName = "admin@tenant.onmicrosoft.com";
string password = "xxxx";


var securePassword = new SecureString();
foreach (char c in password)
{
    securePassword.AppendChar(c);
}

var credentials = new SharePointOnlineCredentials(userName, securePassword);
var ctx = new ClientContext(siteUrl);
ctx.Credentials = credentials;
Web site = ctx.Web;

//Get the required RootFolder
string barRootFolderRelativeUrl = "Shared%20Documents/Demo";
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();
ctx.ExecuteQuery(); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...