Tuesday, October 6, 2015

Upload file to a Document Library with File metadata

Upload file to a Document Library with  File metadata




  public SPListItem UploadFile(SPList listName)
        {
            SPListItem fileItem = null;
            try
            {
                SPWeb web = listName.ParentWeb;

                SPFolderCollection sfc = web.Folders;
                string path = web.Url + "/" + listName.Title.ToString(); // +"/" + fileUpload1.FileName.ToString().Split('.')[0];
                sfc.Add(path);

                SPFile sfile = web.Files.Add(path + "/" + fileUpload1.FileName.ToString() + System.IO.Path.GetExtension(fileUpload1.PostedFile.FileName),
                fileUpload1.FileContent, true);
                listName.Update();
                fileItem = sfile.Item;
            }
            catch (Exception ex)
            {
                Message(lblerror, ex.Message);
            }

            return fileItem; // sfile.Item;

        }

AttachFile To SharePoint ListItem

AttachFile To SharePoint ListItem

  public void AttachFileToItem(SPListItem listItem)
        {
            SPAttachmentCollection attachmentCollection = listItem.Attachments;

            Stream attachmentStream;
            Byte[] attachmentContent;

            // Get the file from the fileupload control
            if (fileUplaod1.HasFile)
            {
                attachmentStream = fileUplaod1.PostedFile.InputStream;

                attachmentContent = new Byte[attachmentStream.Length];

                attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length);

                attachmentStream.Close();
                attachmentStream.Dispose();

                // Add the file to the attachment collection
                attachmentCollection.Add(fileUplaod1.FileName, attachmentContent);
            }

            // Update the list item- SystemUpdate will not create a version
            listItem.SystemUpdate();
       
        }
    }

Monday, October 5, 2015

SharePoint Item Update: Exception Handling when Item is null or Empty

SharePoint Item Update: Exception Handling when Item is null or Empty


item["ProgramTitle"] = (wpItem["ProgramTitle"] != null) ? wpItem["ProgramTitle"].ToString() : string.Empty;