Search code examples
sharepoint-2010

Upload Documents to share point 2010 Document library


it is my first time to work with share point 2010 , I need an easy way to upload documents to share point 2010 pragmatically I have searched for it but always there is a fake error I want an easy and clear way to do that using c# with share point 2010 Thanks in advance :)


Solution

  • You need to try the code. No one put the perfect code for your case may be they put something like "mymethod" or my "Param". Any way, you can use this:

    String fileToUpload = @"C:\YourFile.txt";
            String sharePointSite = "http://yoursite.com/sites/Research/";
            String documentLibraryName = "Shared Documents";
    
            using (SPSite oSite = new SPSite(sharePointSite))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (!System.IO.File.Exists(fileToUpload))
                        throw new FileNotFoundException("File not found.", fileToUpload);                    
    
                    SPFolder myLibrary = oWeb.Folders[documentLibraryName];
    
                    // Prepare to upload
                    Boolean replaceExistingFiles = true;
                    String fileName = System.IO.Path.GetFileName(fileToUpload);
                    FileStream fileStream = File.OpenRead(fileToUpload);
    
                    // Upload document
                    SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
    
                    // Commit 
                    myLibrary.Update();
                }
            }
    

    You can find the article on my blog:
    http://eslamsoliman.blogspot.com/2011/05/how-to-upload-file-to-share-point.html