У меня больше нет идей. Я хочу создать новый элемент в 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;
}