Freigeben über


Using the SharePoint 2010 Client OM with Open XML - Modifying a Document

This is a clipboard friendly version of example #2, Modifying a Document, from Using the SharePoint 2010 Managed Client Object Model with Open XML.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOC

using System;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.SharePoint.Client;
using ClientOM = Microsoft.SharePoint.Client;

class Program
{
static private void CopyStream(Stream source, Stream destination)
{
byte[] buffer = new byte[32768];
int bytesRead;
do
{
bytesRead = source.Read(buffer, 0, buffer.Length);
destination.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}

static void Main(string[] args)
{
ClientContext clientContext =
new ClientContext("https://intranet.contoso.com");
List sharedDocumentsList = clientContext.Web.Lists
.GetByTitle("Shared Documents");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='FileLeafRef'/>
<Value Type='Text'>Test.docx</Value>
</Eq>
</Where>
<RowLimit>1</RowLimit>
</Query>
</View>";
ListItemCollection listItems =
sharedDocumentsList.GetItems(camlQuery);
clientContext.Load(sharedDocumentsList);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
if (listItems.Count == 1)
{
ClientOM.ListItem item = listItems[0];
Console.WriteLine("FileLeafRef: {0}", item["FileLeafRef"]);
Console.WriteLine("FileDirRef: {0}", item["FileDirRef"]);
Console.WriteLine("FileRef: {0}", item["FileRef"]);
Console.WriteLine("File Type: {0}", item["File_x0020_Type"]);
FileInformation fileInformation =
ClientOM.File.OpenBinaryDirect(clientContext,
(string)item["FileRef"]);
using (MemoryStream memoryStream = new MemoryStream())
{
CopyStream(fileInformation.Stream, memoryStream);
using (WordprocessingDocument doc =
WordprocessingDocument.Open(memoryStream, true))
{
// Insert a new paragraph at the beginning of the
//document.
doc.MainDocumentPart.Document.Body.InsertAt(
new Paragraph(
new Run(
new Text("Newly inserted paragraph."))), 0);
}
// Seek to beginning before writing to the SharePoint server.
memoryStream.Seek(0, SeekOrigin.Begin);
// SaveBinaryDirect replaces the document on the SharePoint
// server.
ClientOM.File.SaveBinaryDirect(clientContext,
(string)item["FileRef"], memoryStream, true);
}
}
else
Console.WriteLine("Document not found.");
}
}