lundi 16 mars 2015

Upload wordprocessing document to SharePoint list



I am trying to upload a document from my drive were I make a copy of my .docx file and then remove header and footer and then upload to my list.


I can open my document that I upload, but I get an error when opening it:



We are sorry we cant open lala.docs because we found a problem with its contents




using (SPWeb web = mysites.RootWeb)
{
using (mysites.OpenWeb())
{

SPList list = web.Lists["Arbetskopior för dokument"] as SPDocumentLibrary;
string file = fileName;


using (MemoryStream destination = new MemoryStream())
{
//FileInfo f = new FileInfo(file);

var exten = Path.GetExtension(file);
if (file.Length > 0 && exten == ".docx")
{


using (Stream sourcefilecopy = File.OpenRead(file))
{
sourcefilecopy.CopyTo(destination);

using (WordprocessingDocument doc = WordprocessingDocument.Open(destination, true))
{

var docPart = doc.MainDocumentPart;

if (docPart.HeaderParts.Count() > 0 ||
docPart.FooterParts.Count() > 0)
{
docPart.DeleteParts(docPart.HeaderParts);
docPart.DeleteParts(docPart.FooterParts);
Document document = docPart.Document;
var headers = document.Descendants<HeaderReference>().ToList();
foreach (var header in headers)
{
header.Remove();
}

var footers = document.Descendants<FooterReference>().ToList();
foreach (var footer in footers)
{
footer.Remove();
}
document.Save();

var byteArray = new byte[sourcefilecopy.Length];
string filename = System.IO.Path.GetFileName(file);
sourcefilecopy.Read(byteArray, 0, (int)sourcefilecopy.Length);
sourcefilecopy.Close();

bool addFilesNotExisting = true;
string fileUrl = list.RootFolder.Url + "/" + filename;


SPFile fileSp = list.RootFolder.Files.Add(fileUrl, byteArray, addFilesNotExisting);
SPListItem item = fileSp.Item;

item["Namn"] = fileSp.Name;


}

}
item.Update();







0 commentaires:

Enregistrer un commentaire