Tuesday, September 13, 2011

Upload document in document library with content type in sharepoint

Hi Friend,
I am going to write simple steps to upload document in document library with content type. I know that most of the people are aware about it but this simple post can help for new friends.

First Thing is, i want to explain about business requirements: Get content type name, multiple document source path, sharepoint library URL and file extensions from the configuration file (web.config).

1. First create two content type in your site.
 Go to your site-->Site Settings-->Click "Site content Types" from galleries section-->Click "Create"-->Put "wvOCSImage" in name textbox--->"select document content type" from "select parent content type from:" dropdown-->Select "document" from parent content type dropdown-->Select "Custom Content Type" as group and click ok.

Do the same for second content type and give name  "wvOCSDoc".

2. Now here is my <appsettings> of application web.config file

Go to C:\inetpub\wwwroot\wss\VirtualDirectories\ and open your application web.config file and copy and paste below settings just before </configuration> tab.

<appSettings>
    <add key="IMGcType" value="wvOCSImage" />
    <add key="DoccType" value="wvOCSDoc" />
    <add key="sourcePath" value="C:\Document File Path\Image,C:\Document File Path\Video,D:\Document\Audio,C:\BusinessDoc" />
    <add key="SPLibraryURL" value="http://servername:portno./Content%20Library/Forms/AllItems.aspx" />
    <add key="defaultImage" value="JPG,BMP,jpeg" />
     <add key="defaultDoc" value="DOC,docx" />
  </appSettings>

3. Open visual studio and create custom webpart. and copy and paste below code in pageload event. (You may use same code at any other event as per your requirement)

        String ImgContentType = default(String);
        String DocumentContentType = default(String);
        String sourcepath = default(String);
        String SPLibrarypath = default(String);
        String DefaultImage = default(String);
        String DefaultDoc = default(String);
       
        string[] IndividualSource = new string[];
        string[] IndividualImage;
        string[] IndividualDoc;

            if (ConfigurationManager.AppSettings["IMGcType"] != null)
            {
                ImgContentType = ConfigurationManager.AppSettings["IMGcType"].ToString().Trim();
            }

            if (ConfigurationManager.AppSettings["DoccType"] != null)
            {
                DocumentContentType = ConfigurationManager.AppSettings["DoccType"].ToString().Trim();
            }
            if (ConfigurationManager.AppSettings["sourcePath"] != null)
            {
                sourcepath = ConfigurationManager.AppSettings["sourcePath"].ToString().Trim();
                // separate individual items by commas
                IndividualSource = sourcepath.Split(new char[] { ',' });
            }
            if (ConfigurationManager.AppSettings["SharepointargetPath"] != null)
            {
                SPLibrarypath = ConfigurationManager.AppSettings["SPLibraryURL"].ToString().Trim();
            }

            if (ConfigurationManager.AppSettings["defaultImage"] != null)
            {
                DefaultImage = ConfigurationManager.AppSettings["defaultImage"].ToString().Trim();
                // separate individual items between commas
                IndividualImage = DefaultImage.Split(new char[] { ',' });
            }

            if (ConfigurationManager.AppSettings["defaultDoc"] != null)
            {
                DefaultDoc = ConfigurationManager.AppSettings["defaultDoc"].ToString().Trim();
                // separate individual items between commas
                IndividualDoc = DefaultDoc.Split(new char[] { ',' });

            }

            //get single image file, check extension and upload into document library

            string[][] AllExtensions = new string[][] { IndividualImage, IndividualDoc };
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spCurrentSite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb spCurrentweb = spCurrentSite.OpenWeb(SPContext.Current.Web.ID))
                    {
                        spCurrentweb.AllowUnsafeUpdates = true;
                        SPList _Listname = spCurrentweb.GetList(SPLibrarypath);

                        SPContentType WebImageContentType = null;
                        SPContentType WebDocContentType = null;

                        if (_Listname != null)
                        {
                            SPContentType ImageCT = _Listname.ContentTypes[ImgContentType];
                            SPContentType DocumentCT = _Listname.ContentTypes[DocumentContentType];

                            // Enable Content Types on list
                            _Listname.ContentTypesEnabled = true;

                            if (ImageCT == null)
                            {
                                WebImageContentType = spCurrentweb.AvailableContentTypes[ImgContentType];
                                _Listname.ContentTypes.Add(WebImageContentType);
                            }

                            if (DocumentCT == null)
                            {
                                WebDocContentType = spCurrentweb.AvailableContentTypes[DocumentContentType];
                                _Listname.ContentTypes.Add(WebDocContentType);

                            }

                            // Update List Configuration
                            _Listname.Update();

                            foreach (string dirpath in IndividualSource)
                            {
                                string[] Source = Directory.GetFiles(dirpath);

                                foreach (string imagefile in Source)
                                {
                                    for (int row = 0; row < AllExtensions.Length; row++)
                                    {
                                        foreach (string element in AllExtensions[row])
                                        {
                                            if (imagefile.ToLower().EndsWith(element.ToString()) || imagefile.ToUpper().EndsWith(element.ToString()))
                                            {
                                                //Add document to library
                                                StreamReader sr = new StreamReader(imagefile);
                                                Stream fStream = sr.BaseStream;
                                                byte[] contents = new byte[fStream.Length];
                                                fStream.Read(contents, 0, (int)fStream.Length);
                                                fStream.Close();
                                                fStream.Dispose();

                                                string fileName = Path.GetFileName(imagefile);
                                                string destUrl = _Listname.RootFolder.ServerRelativeUrl + "/" + fileName;

                                                foreach (string extension in IndividualImage)
                                                {
                                                    if (extension.Equals(element))
                                                    {
                                                        SPFile addedFile = _Listname.RootFolder.Files.Add(destUrl, contents, true);
                                                        SPItem newItem = addedFile.Item;
                                                        newItem["ContentType"] = WebImageContentType.Name;
                                                        newItem.Update();
                                                        addedFile.Update();
                                                        break;
                                                    }
                                                }

                                                foreach (string extension in IndividualDoc)
                                                {
                                                    if (extension.Equals(element))
                                                    {
                                                        SPFile addedFile = _Listname.RootFolder.Files.Add(destUrl, contents, true);
                                                        SPItem newItem = addedFile.Item;
                                                        newItem["ContentType"] = WebDocContentType.Name;
                                                        newItem.Update();
                                                        addedFile.Update();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        else
                        {
                            //List name is not found error
                        }
                        spCurrentweb.AllowUnsafeUpdates = false;
                    }
                }
            });
 Now you can go to your library and can see both the content types have been added and all the files from your physical source have been uploaded in document library with content type name. This is just the sample code you can change based on your requirement.\
Please provide your feedback

1 comment:

  1. wouldn't it be nice to be able to use programs such as limewire or adobe or media players without the unexpected crashes or malware ie spam? I am curious on your thoughts?or remedies.thank you for your time.

    ReplyDelete