Search code examples
c#sharepointfile-iowindows-sharepoint-services

Sharepoint adding an item into a Picture Library


I would like to add an item into a picture Library using c#. This is how I would add a field to a normal item:

var item = list.Items.Add();
item["Title"] = "Item title";
item.Update();

How would I go about adding the picture? The picture is stored on the file system i.e. c:\myfile.png I iamgine I need to use SPFile but not sure how.


Solution

  • Here's a method to create a byte[] from the file

    private byte [] StreamFile(string filename)
    {
      FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);
      // Create a byte array of file stream length
      byte[] ImageData = new byte[fs.Length];
      //Read  block of bytes from stream into the byte array
      fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));
      //Close the File Stream
      fs.Close();
      return ImageData;
    }
    
    // then use the following to add the file to the list
    list.RootFolder.Files.Add(fileName, StreamFile(fileName));