28 May 2010

programmatically update a file in document library

Wondering how to how to update file in document library? Well, if you want to programmatically update a document and save it back to the document library.. here is the code for that
public void UpdateDocument()
{
 System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

 SPSecurity.RunWithElevatedPrivileges(delegate()
 {
  using (SPSite siteColl = new SPSite("http://localhost:8080/"))
  {
   using (SPWeb web = siteColl.OpenWeb())
   {
    try
    {   
     SPFile spfile = web.GetFile("http://localhost:8080/Lists/DemoLib/abc.txt");
     if (spfile.Exists)
     {
      byte[] byteArrayFileContentsBefore = spfile.OpenBinary();

      if (byteArrayFileContentsBefore.Length > 0)
      {
       string strFileContentsBefore = enc.GetString(byteArrayFileContentsBefore); //convert byte array to string.
       string newStr = strFileContentsBefore + "This is the new text added";
       byte[] byteArrayFileContentsAfter = null;
       if (!newStr.Equals(""))
       {
        byteArrayFileContentsAfter = enc.GetBytes(newStr);
        spfile.SaveBinary(byteArrayFileContentsAfter); //save to the file.
       }
      }
     }
    }
    catch (Exception e){}
   } 
  }
 });
}

SPFile has a CopyFile method which can copy the file to a new location. But if there was an existing file on the new location, you can set the overwrite parameter to true to overwrite it. Here is a problem, supposingly there was a workflow already on the file in the new location... when you use CopyFile.. the workflow is lost.. basically it is not an update of the file.. it is infact a delete and re-adding of the file. The following code will overcome this problem

private void UpdateDocumentForERB_ExecuteCode(SPWeb web, string originalFileUrl, string targetFileUrl)
{
 SPSecurity.RunWithElevatedPrivileges(delegate()
 {
  SPFile OriFile = web.GetFile(originalFileUrl);
  SPFile TarFile = web.GetFile(targetFileUrl);

  byte[] byteArrayOriFile = OriFile.OpenBinary();

  TarFile.SaveBinary(byteArrayOriFile);

 });

}

3 comments:

  1. Hello, great post!

    Friend, you know where I can somehow accomplish the following task:
    add a string directly into the body document, this information will be generated in a sharepoint column whenever a new document is created. thanks!

    ReplyDelete
  2. Hi Great Reply,

    I am uploading the document's thourgh WebServies. am able to upload documents into sharepoint2010, but after refreshing the sharepoint page only that uploaded document is appearing.

    let em know the hint that, after uploading the document automatically the page has to be refresh and document has to be display.

    pls...

    ReplyDelete
  3. Hello ,

    Great post, I have implement above code but when i try to open the document it is not opening.Any prefix for this

    Thanks
    Rohit

    ReplyDelete