none
ClientContext -> Add List Item w/ Attachment

    Dotaz

  • I'm having some issues finding a solution on how to do this. I think I've been able to get pretty close but haven't quite figured it out. See the code below:

    try
    {
      ClientContext client = new
      ClientContext(siteUrl);
      NetworkCredential credentials = new NetworkCredential("username", "password", "domain");
      client.Credentials = credentials;
     
      Web thisWeb = client.Web;
      client.Load(thisWeb);
      List ChangeRequestList = thisWeb.Lists.GetByTitle("Change Requests");
      client.Load(ChangeRequestList);
    
      ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
      Microsoft.SharePoint.Client.ListItem oListItem = ChangeRequestList.AddItem(itemCreateInfo);
      
      System.Guid ticket = System.Guid.NewGuid();
    
      oListItem["Title"] = ticket.ToString();
      oListItem["Mall"] = Session["strUserID"].ToString();
      oListItem["Body"] = Submit_Changes.Text;
      oListItem["Submitted_x0020_By"] = Submit_Name.Text;
      oListItem["Contact_x0020_E_x002d_mail"] = Submit_Email.Text;
      oListItem["Contact_x0020_Phone"] = Submit_Phone.Text;
      oListItem.Update();
    
      if (Submit_FileUpload.HasFile)
      {
       FileCreationInformation fileAttachment = new
     FileCreationInformation();
       fileAttachment.Content = Submit_FileUpload.FileBytes;
       fileAttachment.Url = Submit_FileUpload.FileName;
    
       SP.File uploadFile = ChangeRequestList.RootFolder.Files.Add(fileAttachment);
       client.Load(uploadFile);
      }
    
      client.ExecuteQuery();
      client.Dispose();
    }

    So the above code creates the ListItem just fine, it even uploads the file. However, it does not add the attachment within the actual ListItem. The image shows in the following directory:

       http://localhost/testing/Lists/Change%20Requests/500x_chrisandrewsspring.jpg

    it should however be in this directory:

       http://localhost/testing/Lists/Change%20Requests/Attachments/1/500x_chrisandrewsspring.jpg

     

    What am I doing wrong? I've noticed when using Microsoft.SharePoint you should be able to use ListItem.Attachment and/or ListItem.AttachmentCollection. However, I have neither of these when using the Microsoft.SharePoint.Client DLL's since I'm accessing this list from an external source.

     

    Thanks in advance.

     

    15. dubna 2010 21:24

Všechny reakce

  • The client OM makes it easy to upload files directly without having to bring down any of the associated data for the item. Just use File.SaveBinaryDirect. Below is some example code. I had to alias System.IO since there is a confilict with this namespace and the client OM.

    public static void AddListItemAttachment(string attachFilePath, string listUrl, string itemId)
    {
      
          ClientContext clientContext = new ClientContext(listUrl);
          Uri url = new Uri(listUrl);
    
          using (IO.FileStream strm = new IO.FileInfo(attachFilePath).Open(IO.FileMode.Open))
          {
            File.SaveBinaryDirect(clientContext, url.AbsolutePath + "/Attachments/" + itemId + "/" + IO.Path.GetFileName(attachFilePath), strm, true);     
          }
           
    }

    certdev.com
    17. dubna 2010 4:23
  • how do you do the same thing using silverlight client object model? There is no SaveBinaryDirect()...
    17. dubna 2010 20:57
  • You can try the following approach. I have not tested it yet:

     public static void AddAttachement(byte[] attachFile, int itemId, string fileName)
    {
          ClientContext clientContext = new ClientContext("http://basesmc2008");
         
          Folder attachments = clientContext.Web.GetFolderByServerRelativeUrl("/Lists/Attachments/Attachments");
          FileCreationInformation fci = new FileCreationInformation();
    
          fci.Overwrite = true;
          fci.Content = attachFile;
          fci.Url = fileName;
        
          attachments.Folders[itemId].Files.Add(fci);
    
          clientContext.ExecuteQueryAsync((object eventSender, ClientRequestSucceededEventArgs eventArgs) =>
          {
    
            string ret;
            if (eventArgs.Request != null)
              ret = eventArgs.Request.ToString();
    
          }, null);
    
    
        }
    
      }
    }

    certdev.com
    • Navržen jako odpověď Francisco83 13. ledna 2011 18:50
    18. dubna 2010 23:59
  • Hello People!! =)

    I have a little help too, im try create items with attachment from a Windows Form and using Client Object Model, but the other replys don´t work me because i don't know the item id.

    Look my code

    Please i need help

    Thanks very much.

     

    public string NewItemAdjunto(string _nombreLista, string _url, string _titulo, string _detalles, string _pathArchivo)
        {
          try
          {
            //Variables Locales
            string nombreArhivo;
    
            //MANIPULACIÓN DEL ARCHIVO
            
            using (FileStream fs = System.IO.File.OpenRead(_pathArchivo))
            {
              nombreArhivo = Path.GetFileName(_pathArchivo);
              //creamos arreglo de binarios
              byte[] b = new byte[fs.Length];
           
              //CONECTA CON SHAREPOINT E INGRESA ITEMS CON ADJUNTOS
              
              using (ClientContext ctx = new ClientContext(_url))
              {
                Uri url = new Uri(_url);
                Web site = ctx.Web;
                ctx.Load(site);
                List lista = ctx.Web.Lists.GetByTitle(_nombreLista);
                ctx.Load(lista);
             
                ListItemCreationInformation newInfo = new ListItemCreationInformation();
                ListItem item = lista.AddItem(newInfo);
        
                // ADD VALUES 
                item["Title"] = _titulo;
                item["Descripci_x00f3_n"] = _detalles;
                item["Fecha"] = new DateTime(2010, 11, 10, 8, 0, 0);// Force DATE
    		//ADD ATTACHMENT
             // Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, url.AbsolutePath + "/Attachments/" + itemId + "/" + IO.Path.GetFileName(attachFilePath), strm, true);   
    
    		
                ctx.ExecuteQuery();
    
              }
            }
    
    
            
    
    
            //RETORNA RESULTADO EXITOSO
            return "Item con Adjunto Creado";
            
          }
          catch
          {
            throw;
          }
          
        }
    
    10. listopadu 2010 21:15
  • Steve,

     

         I am getting Security Exception while reading the file from Silverlight by using the above example. The error was "File operation not permitted. Access to path 'C:\OneNote\DMB Members1\9-10 referatsaker.one' is denied". Please help me to resolve this issue.


    Balaji
    30. prosince 2010 9:24
  • Hi,

    I am working with a list which contains an attached image.

    my problem is that I dont know how to get/read this attachment as I need to display it as an Icon for my list of links.

    first it is a custom list and has this custom field

    <Field ID="{C60E786A-0B4A-4797-A5C0-77CD2939340A}"          Type="Attachments"          Name="Icon"          DisplayName="Icon"          Description="Icon of the System or Tool"          Format="Image"          Required="TRUE"          Sealed="TRUE" />

    The user can add new items to the list and attach images which I want to display as icons when reading the list.

    Do you know how can it be done?

    I am using the following code to read the list and retreive all the items

                    SPWeb web = SPContext.Current.Web;
                    SPSiteDataQuery query = new SPSiteDataQuery();
     
                    query.Lists = "<Lists><List ID=\"" + listGUID + "\" /></Lists>";
     
                    // Get the Title, Url and Description fields.
                    query.ViewFields = "<FieldRef Name=\"Title\" />" +
                                       "<FieldRef Name=\"Icon\" Nullable=\"TRUE\" Type=\"Attachments\"/>" +
                                       "<FieldRef Name=\"Url\" Nullable=\"TRUE\" Type=\"Text\"/>" +
                                       "<FieldRef Name=\"Description\" Nullable=\"TRUE\" Type=\"Text\"/>";
     
                    query.Query = "<OrderBy><FieldRef Name =\"Title\" /></OrderBy>";
     
                    query.Webs = "<Webs Scope=\"SiteCollection\" />";
     
                    DataTable dt = web.GetSiteData(query);
                    cb_SelectedSt.Items.Clear();
                    if (dt.Rows.Count > 0)
                    {
                        lbl_Itemslist.Visible = true;
                        lbl_Itemslist.Text = "Systems and/or Tools";
                        foreach (DataRow row in dt.Rows)
                        {
                            cb_SelectedSt.Visible = true;
                            if (row != null)
                            {
                                // creating the link
                                STLinksList= "<a href=\"" + row["Url"].ToString() + "\"" + SetNewWindow.ToString() +
                                             " title=\"" + row["Description"].ToString() + " " + row["Url"].ToString() + "\">" +
                                             // here I need to get the attached image and display it
     
                                             row["Title"].ToString() + "</a>";
                                cb_SelectedSt.Items.Add(new ListItem(STLinksList, row["ID"].ToString()));
                            }
                        }
                    }

    any suggestion?

    thanks in advance

    13. června 2012 17:23
  • SJBravo, you have already created a thread for your question, so there's no need to clutter up this one. Aspheris'  issue has no relations to yours 

    Kind Regards Bjoern
    Blog

    13. června 2012 18:06