Skip to content

Instantly share code, notes, and snippets.

@zplume
Last active May 29, 2019 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zplume/107f46f228312aea9290b4721765166b to your computer and use it in GitHub Desktop.
Save zplume/107f46f228312aea9290b4721765166b to your computer and use it in GitHub Desktop.
Example of using CsvHelper to write a CSV file (up to 10MB in size) to SharePoint Online
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using OfficeDevPnP.Core;
using Microsoft.SharePoint.Client;
using System.IO;
using CsvHelper;
using File = Microsoft.SharePoint.Client.File;
using CsvHelper.Configuration.Attributes;
public class CsvRow
{
[Index(0)]
public DateTime TimeStamp { get; set; }
[Index(1)]
public string SiteUrl { get; set; }
[Index(2)]
public string Message { get; set; }
[Index(3)]
public string Level { get; set; }
public CsvRow() {}
}
public class CsvHelperExample
{
public ClientContext ClientContext { get; set; }
public void WriteFile(string listName, string folderName, string fileName, List<CsvRow> csvRows)
{
// load list, get/create folder
List list = ClientContext.Web.GetListByTitle(listName, li => li.RootFolder);
Folder folder = list.RootFolder.EnsureFolder(folderName);
using (MemoryStream stream = new MemoryStream())
{
using (TextWriter writer = new StreamWriter(stream))
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(csvRows);
writer.Flush();
stream.Position = 0;
// write stream to file and upload
using (StreamReader reader = new StreamReader(stream))
{
folder.UploadFile($"{fileName}.csv", stream, true);
}
}
}
}
public CsvHelperExample(ClientContext clientContext)
{
ClientContext = clientContext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment