programmatically Open and save documents in document library SharePoint

The example below has two functions, one for opening and one for saving a specific document in a document library. This code requires the Open XMl SDK, so you will need to download and install it and reference its assembly. In addition, you need to add a reference to the WindowsBase assembly and the Microsoft.SharePoint assembly.

Steps Involved are :

1.Reference the following assemblies in your project

using System.Text;
using System.Threading;
using Microsoft.SharePoint;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

2. Call the OpenDocument function in your code.

Code :

protected void OpenDocument(string siteUrl)
{

using (SPSite spSite = new SPSite(siteUrl))
{

//Get the document from the library using SPQuery
SPList list = spSite.RootWeb.Lists["Shared Documents"];
SPQuery query = new SPQuery();
query.ViewFields ="<FieldRef Name='FileLeafRef' />";
query.Query ="<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>MyDoc.docx</Value></Eq></Where>";

SPListItemCollection collection = list.GetItems(query);

//Get the first document returned. There should be one only.
SPFile file = collection[0].File;
byte[] byteArray = file.OpenBinary();

using (MemoryStream memStr = new MemoryStream())
{
memStr.Write(byteArray, 0, byteArray.Length);

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true))
{

//Getting the document object
Document document = wordDoc.MainDocumentPart.Document;

// Read first paragraph

Paragraph firstParagraph = document.Body.Elements<Paragraph>().FirstOrDefault();

// Now lets append our own paragraph, if document already has text
if (firstParagraph != null)
{
Paragraph testParagraph = new Paragraph(

new Run(new Text("We are Adding this text for Testing!")));
firstParagraph.Parent.InsertBefore(testParagraph,
firstParagraph);
}

//After your done. Lets just save it back. Call the SaveDoc method
SavingDoc(file,memStr);
}

3. Code for Saving the document back in SharePoint.

Protected void SavingDoc(SPFile file, MemoryStream memStr)
{
string linkFileName = string.empty;
linkFileName = file.Item["LinkFilename"].ToString();
file.ParentFolder.Files.Add(linkFileName, memStr, true);
}

To create and add a new document see my post Programmatically Create and upload document in Sharepoint 2010 document library

1 comments:

  1. What if the document is locked out? Can something like this be used to check it back in?

    ReplyDelete

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com