C # - добавление файла как вложения в Microsoft.SharePoint.Client.ListItem (SharePoint 2010)

У меня больше нет идей. Я хочу создать новый элемент в Sharepoint List и добавить файл в качестве вложения. Я могу создать новый элемент с ListItem. Но файл не выгружается.

Я пробую использовать SaveBinaryDirect() функцию и AttachmentCreationInformation() класс. Если я попробую, то получу это исключение

Выброшенное исключение: 'System.Net.WebException' в System.dll (400)

Я также подключился к SharePoint Server и заглянул в журналы Windows, но ничего не нашел.

В свой код я добавляю новый ListItem с lLibrary.AddItem(itemCreateInfo). С ListItem я создаю в SharePoint новый элемент. Этот элемент находится в папке SharePoint. Все это хорошо работает.

Я много пробовал, но ничего не получалось. Мне нужна помощь, пожалуйста!

Вот мой полный код:

public bool UploadToSharepoint(string sURL, string sLibrary, string sFolderName, string sTitel, string sDescription, string sFilePath)
    {
        using (ClientContext clientContext = new ClientContext(sURL))
        {
            if (!SetCredentialsInClientContext(clientContext))
            {
                return false;
            }

            List lLibrary = clientContext.Web.Lists.GetByTitle(sLibrary);

            clientContext.Load(clientContext.Web.Lists);
            clientContext.Load(lLibrary, l => l.RootFolder.ServerRelativeUrl);

            clientContext.ExecuteQuery();

            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
            if (!string.IsNullOrEmpty(sFolderName))
            {
                itemCreateInfo.FolderUrl = lLibrary.RootFolder.ServerRelativeUrl + "/" + sFolderName;
            }

            ListItem newItem = lLibrary.AddItem(itemCreateInfo);

            #region Work only with Document list in SharePoint
            //using (FileStream fs = new FileStream(sFilePath, FileMode.Open))
            //{
            //    clientContext.Load(lLibrary.RootFolder);
            //    clientContext.ExecuteQuery();
            //    string fileUrl = string.Format("{0}/{1}", lLibrary.RootFolder.ServerRelativeUrl, fi.Name);
            //    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, fs, true);
            //}  // Ende using 'FileStream'
            #endregion

            using (FileStream fs = new FileStream(sFilePath, FileMode.Open))
            {
                #region WORK!
                newItem["Title"] = sTitel;
                newItem["Description"] = sDescription;
                newItem.Update();
                clientContext.ExecuteQuery();
                #endregion

                #region SaveBinaryDirect Example NOT WORK
                //using (FileStream strm = new FileInfo(sFilePath).Open(FileMode.Open))
                //{
                //    Uri url = new Uri(sURL);
                //    //Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, url.AbsolutePath + "/Attachments/" + newItem.Id + "/" + fi.Name, strm, true);
                //    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, lLibrary.RootFolder.ServerRelativeUrl + "/Attachments/" + newItem.Id + "/" + fi.Name, strm, true);
                //}

                ////Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, "", fs, true);
                //string serverRelativeUrl = lLibrary.RootFolder.ServerRelativeUrl;
                //Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, serverRelativeUrl, fs, true);
                #endregion

                #region AttachmentCreationInformation Example NOT WORK
                AttachmentCreationInformation attInfo = new AttachmentCreationInformation();
                attInfo.FileName = fs.Name;
                attInfo.ContentStream = fs;
                newItem.AttachmentFiles.Add(attInfo);
                newItem.Update();
                clientContext.ExecuteQuery();
                #endregion
            }
        }
        return true;
    }

РЕДАКТИРОВАТЬ!:

Я совершил большую ошибку. Sharepoint - 2010. Значит, функция AttachmentFiles.Add() не работает.

Я узнал, что мне нужно добавить ссылку на сервис и изменить свой код. Дополнительную информацию можно найти на странице SharePoint 2010 - Модель клиентских объектов - Добавить прикрепление к ListItem

Но теперь я получаю Exception 500. Вот почему я попытался подключиться к Test SharePoint. Там я могу прочитать информацию журнала с сообщением The list does not exist. The selected page contains a list that does not exist. The list could have been deleted by another user.

Я не знаю, какое свойство listName я должен указать для функции AddAttachment(), которая обнаруживает список.

Мой новый код:

public bool UploadToSharepoint(string sURL, string sLibrary, string sFolderName, string sTitel, string sDescription, string sFilePath)
    {
        using (ClientContext clientContext = new ClientContext(sURL))
        {
            if (!SetzeCredentialsInClientContext(clientContext))
            {
                return false;
            }

            List lLibrary = clientContext.Web.Lists.GetByTitle(sLibrary);

            clientContext.Load(lLibrary);
            clientContext.Load(lLibrary.RootFolder);
            clientContext.ExecuteQuery();

            ListItemCreationInformation listItemCreationInformation = new ListItemCreationInformation();
            if (!string.IsNullOrEmpty(sFolderName))
            {
                listItemCreationInformation.FolderUrl = lLibrary.RootFolder.ServerRelativeUrl + "/" + sFolderName;
            }

            var newItem = lLibrary.AddItem(listItemCreationInformation);
            newItem["Title"] = sTitel;
            newItem.Update();
            clientContext.ExecuteQuery();

            clientContext.Load(newItem);
            clientContext.ExecuteQuery();

            TestSP.ListsSoapClient lsc = new TestSP.ListsSoapClient();

            if (_cbAutorisierung.Checked)
            {
                lsc.ClientCredentials.Windows.ClientCredential = new NetworkCredential(tbName.Text, tbPasswort.Text, tbDomain.Text);
            }
            else
            {
                lsc.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            }
            lsc.AddAttachment(sLibrary, newItem["ID"].ToString(), Path.GetFileName(sFilePath), System.IO.File.ReadAllBytes(sFilePath));

        }
        return true;
    }

person Duny    schedule 21.11.2017    source источник
comment
codeproject.com/Questions/602369/   -  person saj    schedule 21.11.2017


Ответы (2)


Наконец-то я приступил к работе!

Проблема заключалась в том, что в конфигурационном файле App.Config Адресс конечной точки явная ссылка на Сайт.

Часть "config" файла:

<system.serviceModel>
<bindings>
  <basicHttpsBinding>
    <binding name="ListsSoap">
      <security>
        <transport clientCredentialType="Ntlm" proxyCredentialType="Ntlm" />
      </security>
    </binding>
  </basicHttpsBinding>
</bindings>
<client>
  <endpoint address="https://TestSharePoint.com/_vti_bin/lists.asmx"
    binding="basicHttpsBinding" bindingConfiguration="ListsSoap"
    contract="SPRivarkom.ListsSoap" name="ListsSoap" />
</client>
</system.serviceModel>

В теге «конечная точка» находится атрибут «адрес». Он содержит адрес веб-ссылки. Но правильный адрес должен быть address="https://TestSharePoint.com/TestSite/TestUnderSite/_vti_bin/lists.asmx".

person Duny    schedule 29.11.2017

Пожалуйста, попробуйте следующий код. Изменили способ формирования URL-адреса папки. Также изменен код, связанный с загрузкой вложений.

В sUrl передайте полный URL-адрес вашего семейства сайтов.

var list = web.Lists.GetByTitle(sLibrary);
clientContext.Load(list);
clientContext.ExecuteQuery();

ListItemCreationInformation listItemCreationInformation = null;
if (!string.IsNullOrEmpty(sFolderName))
{
    listItemCreationInformation = new ListItemCreationInformation();
    listItemCreationInformation.FolderUrl = string.Format("{0}Lists/{1}/{2}", sURL, sLibrary, sFolderName);
}

var listItem = list.AddItem(listItemCreationInformation);
newItem["Title"] = sTitel;
newItem["Description"] = sDescription;
listItem.Update();
clientContext.ExecuteQuery();                

using (FileStream fs = new FileStream(sFilePath, FileMode.Open))
{
    var attInfo = new AttachmentCreationInformation();
    attInfo.FileName = fs.Name;
    attInfo.ContentStream = fs;                    

    var att = listItem.AttachmentFiles.Add(attInfo);
    clientContext.Load(att);
    clientContext.ExecuteQuery();
}
person Gautam Sheth    schedule 22.11.2017
comment
Не работает. Я получаю исключение в строке clientContext.ExecuteQuery () после строки listItem.Update (). Возникло исключение: «Microsoft.SharePoint.Client.ServerException» в Microsoft.SharePoint.Client.Runtime.dll Дополнительная информация: имя файла или папки содержит недопустимые символы. Пожалуйста, используйте другое имя. (Гугл переводчик...) - person Duny; 22.11.2017
comment
Убедитесь, что путь не содержит лишних косых черт. Он должен выглядеть так: sitecollurl / test / lists / libraryname / foldername. - person Gautam Sheth; 22.11.2017
comment
Это уже дано в моем Кодексе. Но проблема не в этом. Я хочу добавить вложение к ListItem. - person Duny; 22.11.2017
comment
Пожалуйста, сверьтесь с отредактированным кодом. Удалили косую черту в пути URL-адреса папки. Я протестировал приведенный выше код в своем окружении, и он работает нормально. Создает элемент списка с вложением - person Gautam Sheth; 22.11.2017
comment
Я пробовал, но дело доходит до этого исключения. Я изменил Код с 'listItemCreationInformation.FolderUrl = string.Format ({0} Lists / {1} / {2}, sURL, sLibrary, sFolderName);' в 'listItemCreationInformation.FolderUrl = lLibrary.RootFolder.ServerRelativeUrl + / + sFolderName;' Поскольку 'sURL' похож на 'SP.com/siteexample/example/Lists/Site/ FolderExample ». Код работает так, что элемент создан. Как прежде. Но теперь я получаю новое сообщение об исключении: «Microsoft.SharePoint.Client.ServerException: данные на корневом уровне недействительны. Строка 2, позиция 1. ' - person Duny; 22.11.2017