3
votes

I have no more ideas. I want to create a new element to Sharepoint List and adding a file as an attachment. I can create a new element with ListItem. But the file will not upload.

I try with SaveBinaryDirect() function and with AttachmentCreationInformation() class. If I try I get this exception

Exception thrown: 'System.Net.WebException' in System.dll (400)

I also connected to the SharePoint Server and looked inside the Windows Logs, but I found nothing.

In my code I add a new ListItem with lLibrary.AddItem(itemCreateInfo). With the ListItem I create in SharePoint a new element. This Element is in SharePoint Folder. This all works well.

I tried a lot but nothing worked. I need help, please!

Here my complete Code:

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;
    }

EDIT!:

I have made a big mistake. The Sharepoint is 2010. So the AttachmentFiles.Add() function is not working.

I found out that I have to add a service reference and change my code. Further information can be found at SharePoint 2010 - Client Object Model - Add attachment to ListItem

But now I get Exception 500. That's why I tried to connect to a Test SharePoint. There I can read the log information with the Message The list does not exist. The selected page contains a list that does not exist. The list could have been deleted by another user.

I do not know what listName property I have to specify for the function AddAttachment() that the list is found.

My new Code:

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;
    }
2

2 Answers

1
votes

Finally I got to work!

The problem was that in the config file App.Config the endpoint Adress explicit reference to the Site.

The Part of "config" File:

<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>

At the tag "endpoint" is the Attribute "adress". This contains the adress of the web reference. But the right adress must be address="https://TestSharePoint.com/TestSite/TestUnderSite/_vti_bin/lists.asmx".

0
votes

Please try the below code. Have modified how the folder url is formed. Also modified some code related to attachment upload.

In the sUrl, please pass the full url of your site collection.

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();
}