Last active
December 28, 2022 22:33
-
-
Save peplau/74bec5478aec49eef87fffbbbfb91c20 to your computer and use it in GitHub Desktop.
(C# code) Parse CSV into memory as a List of Dynamic Objects, with properties named accordingly to the CSV header. This code uses Sitecore Powershell Extensions to run a PS command that does the translation to Dynamic Objects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
------------ | |
Dependencies | |
------------ | |
- Sitecore Powershell Extensions | |
- Add a reference to SPE.dll to your project (CopyLocal=false) | |
------------- | |
Usage example | |
------------- | |
// Get the CSV content - you can load it from a file, but it has to be converted to a string | |
var csvContent = @"FirstName,LastName,Email | |
John,Doe,[email protected] | |
Mary,Smith,[email protected]"; | |
// Parse the string into a List of Dynamic objects | |
var csvList = ParseCsv(csvContent); | |
// Check if it has valid CSV content | |
if (csvList!=null && csvList.Count>0){ | |
// Loop throught all lines of the CSV (skipping the header) | |
foreach(var line in csvList) { | |
// It's better to cast the dynamic object to strongly-typed | |
string firstName = line.FirstName; | |
string lastName = line.LastName; | |
string email = line.Email; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Spe.Core.Host; | |
using System.Reflection; | |
/// <summary> | |
/// Load CSV string to memory as array of dynamic objects | |
/// </summary> | |
/// <param name="csvContent"></param> | |
/// <returns>Array of dynamic objects</returns> | |
public dynamic ParseCsv(string csvContent) { | |
using (var scriptSession = ScriptSessionManager.NewSession("Default",true)) { | |
// Pass the CSV string to Powershell as a variable | |
scriptSession.SetVariable("csvContent", csvContent); | |
// Unfortunatelly the method with the overloads we need is internal, so let's use reflection | |
var methodInfo = typeof(ScriptSession).GetMethod("ExecuteScriptPart", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(string), typeof(bool), typeof(bool), typeof(bool) }, null); | |
// Execute the PS command, cast and return | |
return (List<dynamic>)methodInfo.Invoke(scriptSession, new object[] {"$csvContent | ConvertFrom-Csv", false, false, false}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment