Question

I wish to add title and description to image. So I am trying below code

byte[] converttobyte= webClient.DownloadData(imageUrl);
var imageId = image.SelectToken("id");
 using (var site = new SPSite(sharePointSite))
 {
      using (SPWeb web = site.OpenWeb())
      {
       SPPictureLibrary pics = (SPPictureLibrary)web.Lists[documentLibraryName];

        pics.RootFolder.Files.Add((string) imageId + ".jpg", converttobyte, true);
        SPList list = web.Lists["MyImages"];
        SPListItem item = list.Items.Add();
        item["Title"] = "First title ";
        item["Description"] = "Test Description is " ;
        item.Update();
    }
}

But i get error on item.update

To add an item to a document library, use SPFileCollection.Add()

What is wrong here and How I can do to resolve it?

Was it helpful?

Solution

Update your code as below

SPPictureLibrary pics = (SPPictureLibrary)web.Lists[documentLibraryName];

SPFile file = pics.RootFolder.Files.Add((string) imageId + ".jpg", converttobyte, true);
SPListItem item = file.Item;
item["Title"] = "First title ";
item["Description"] = "Test Description is " ;
item.Update();

The issue in your code is that you are trying to create a ListItem on a Document Library.

Files.Add method returns an SPFile object. This object has a property Item which points to the SPListItem associated with the File. Now to update metadata you need to update that SPListItem.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top