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 SPQuerySPList 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 objectDocument document = wordDoc.MainDocumentPart.Document;
// Read first paragraphParagraph firstParagraph = document.Body.Elements<Paragraph>().FirstOrDefault();
// Now lets append our own paragraph, if document already has textif (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 methodSavingDoc(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