Sharepoint adds item to image library

I would like to add an item to an image library using C #. This is how I would add a field to a regular element:

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

      

How can I add an image? The picture is stored in the file system, ie c: \ myfile.png i iamgine I need to use SPFile but not sure how.

+2


source to share


2 answers


Here's a method to create byte [] from 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));

      

+3


source


It's as easy as adding a file to Lib Lib. Below is a code snippet to help you do this. I am taking the code from this link as the formatting is not correct where I pasted the clean version here



try
        {
            byte[] imageData = null;
            if (flUpload != null)
            {
                // This condition checks whether the user has uploaded a file or not
                if ((flUpload.PostedFile != null) && (flUpload.PostedFile.ContentLength > 0))
                {
                    Stream MyStream = flUpload.PostedFile.InputStream;
                    long iLength = MyStream.Length;
                    imageData = new byte[(int)MyStream.Length];
                    MyStream.Read(imageData, 0, (int)MyStream.Length);
                    MyStream.Close();
                    string filename = System.IO.Path.GetFileName(flUpload.PostedFile.FileName);                                                
                   SPPictureLibrary pic = (SPPictureLibrary)SPContext.Current.Web.Lists["Images"];//Images is the picture library name
                   SPFileCollection filecol = ((SPPictureLibrary)SPContext.Current.Web.Lists["Images"]).RootFolder.Files;//getting all the files which is in pictire library
                   filecol.Add(filename, imageData);//uploading the files to picturte library

                }
            }                
        }
        catch (Exception ex)
        {
            //handle it
        } 

      

+1


source







All Articles