Monday, June 10, 2013

Programmatically Add/Upload a file to Document Library in SharePoint 2010

Simple steps to upload a file programmatically to SPDocumentLibrary in SharePoint 2010


using (SPSite site = newSPSite("http://mySharePointServer"))
  {

using (SPWeb web = site.OpenWeb())
  {

SPSecurity.RunWithElevatedPrivileges(delegate()
               {

SPDocumentLibrary documentLib = web.Lists["YourLibraryName"] as SPDocumentLibrary;

Stream fStream = FileUpload1.PostedFile.InputStream;
byte[]  _byteArray = new byte[fStream.Length];
fStream.Read(_byteArray, 0, (int)fStream.Length);
fStream.Close();

web.AllowUnsafeUpdates = true;

string _fileUrl = documentLib.RootFolder.Url + "/" + FileUpload1.PostedFile.FileName;

bool IsOverwriteFile = true;
SPFile file = documentLib.RootFolder.Files.Add(_fileUrl, _byteArray, IsOverwriteFile);

SPListItem item = file.Item;
item["Title"] = FileUpload1.PostedFile.FileName;
item.Update();
file.Update();

web.AllowUnsafeUpdates = false;
              
      });           
 }
      
 }


Adding Folder and SubFolder to document library in SharePoint 2010

using (SPSite site = new SPSite("http://mySharePointServer"))
  {

   using (SPWeb web = site.OpenWeb())
   {

   SPSecurity.RunWithElevatedPrivileges(delegate()
     {

      SPDocumentLibrary documentLib = web.Lists["TestLib"] as SPDocumentLibrary;
      web.AllowUnsafeUpdates = true;

     SPListItem newFolder = documentLib.Items.Add("", SPFileSystemObjectType.Folder, "TestRootFolder");

   newFolder.Update();

//Creating Subfolder inside folder
stringsubFolderUrl = web.Url + "/" + newFolder.Url;

SPListItem subFolder = documentLib.Items.Add(subFolderUrl, SPFileSystemObjectType.Folder, "TestSubFolder");

subFolder.Update();

web.AllowUnsafeUpdates = false;

                });
            }

        }

---
Thanks

2 comments:

  1. il y'a une erreur sur cette ligne
    string _fileUrl = documentLib.RootFolder.Url + "/" + FileUpload1.PostedFile.FileName;

    il faut essayer celle la

    string _fileUrl = documentLib.RootFolder.Url + "/" + Path.GetFileName(FileUpload1.PostedFile.FileName);

    ReplyDelete