2

I have a fairly large CSV file (27MB) with at least 400,000 rows in it. I want to add a column to it, just like in this method and export it, except that I have to do it in C#. I have added the System.Management.Automation and the Microsoft.PowerShell namespaces. I would also like the new column to be the first column in the CSV. How might I be able to achieve this in the fastest way possible?

While the method used here could work, I specifically do not want to use any custom libraries not provided by windows.

This is what I've tried, but it doesn't seem to work:

PowerShell ps = PowerShell.Create();
ps.AddCommand("Import-Csv " + csvFileName + " |Select-Object *,@{Name='Name' ;Expression = {'setvalue'}} | Export-Csv " + csvFileName + " -NoTypeInformation");
ps.Invoke();
Community
  • 1
  • 1
Alfred Waligo
  • 2,809
  • 3
  • 18
  • 26

1 Answers1

3

I solved the problem by changing the ps.AddCommand to ps.AddScript and surrounding the csvFileName with single quotes. The modified code is as follows

PowerShell ps = PowerShell.Create();
ps.AddScript("Import-Csv '" + csvFileName + "' |Select-Object *,@{Name='Name' ;Expression = {'setvalue'}} | Export-Csv '" + newCsvFileName + "' -NoTypeInformation");
ps.Invoke();
Alfred Waligo
  • 2,809
  • 3
  • 18
  • 26