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


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.


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
  //Close the File Stream
  return ImageData;

// then use the following to add the file to the list
list.RootFolder.Files.Add(fileName, StreamFile(fileName));




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

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




All Articles