Sunday, March 4, 2012

Article 3: Create new document sets and upload document using webpart


Download source at here

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using Microsoft.Office.DocumentManagement.DocumentSets;//Add reference
using Microsoft.SharePoint;
using System.IO;


namespace SPTWPNewPurchaseRQ.SPTWPNewPurchaseRQ
{
    public partial class SPTWPNewPurchaseRQUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            txtDateRequest.Text = DateTime.Now.ToShortDateString();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (txtTitle.Text != "")
            {
                SPWeb spWeb = SPContext.Current.Web;
                String documentLibraryName = @"PurchaseRequest";//   
                SPList purchaseRequest = spWeb.Lists["PurchaseRequest"];
                SPContentType documentSetContentType = purchaseRequest.ContentTypes["FinanceDoc"];//FinanceDoc name of Content Type
                //Declare to get File Name
                string documentSetName = txtTitle.Text;
                //Declare Hashtable
                Hashtable properties = new Hashtable();
                properties.Add("DocumentSetDescription", txtDescription.Text);//DocumentSetDescription => InternalName
                properties.Add("Date1", txtDateRequest.Text);
                properties.Add("DepartmentRequest", ddlDepartment.SelectedValue.ToString());
                properties.Add("Total", txtTotal.Text);

                SPFolder parentFolder = purchaseRequest.RootFolder;
                //Create new Document sets
                DocumentSet.Create(parentFolder, documentSetName, documentSetContentType.Id, properties, true);
                //Declare to upload file to document set, only run on IE
                String fullPathFileName = fileUpload1.PostedFile.FileName;
                //Check file is exists?
                if (!System.IO.File.Exists(fullPathFileName))
                    throw new FileNotFoundException("File not found.", fullPathFileName);
                //Declare path to document set
                SPFolder myLibraryToUploadDocument = spWeb.Folders[documentLibraryName].SubFolders[txtTitle.Text];
                // Prepare to upload
                Boolean replaceExistingFiles = true;
                String fileName = System.IO.Path.GetFileName(fullPathFileName);
                FileStream fileStream = File.OpenRead(fullPathFileName);
                // Upload document
                SPFile spfile = myLibraryToUploadDocument.Files.Add(fileName, fileStream, replaceExistingFiles);
                // Commit
                myLibraryToUploadDocument.Update();
                //web.GetFile(web.Url + "/" + destinationFolderUrl + file.Name);
            }
        }
    }
}

0 comments:

Post a Comment