Monday 9 February 2015

Upload file into sharepoint document library

Here is the code:

String documentLibraryName = "Documents";
            using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))  
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (!FileUpload1.HasFile)//Check file is selected or not
                        throw new FileNotFoundException("File not found.", FileUpload1.FileName);
                    SPFolder myLibrary = oWeb.Folders[documentLibraryName];//Access the document library
                    // Prepare to upload
                    bool replaceExistingFiles = true;
                    String fileName = System.IO.Path.GetFileName(FileUpload1.FileName);//get Filename
                    Stream fileStream = FileUpload1.PostedFile.InputStream;//Get filesstream from uploadcontrol
                    SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);// Upload document
                    myLibrary.Update();// Commit
                }
            }