To reorder the columns of a CSV file in C#, you can use the Linq library to read the file, reorder the columns, and write them out to a new file.
Assuming your CSV file has a header row with column names and the columns you want to reorder are known ahead of time, you could use the following code:
main.cs916 chars31 lines
This code reads the CSV file into an array of strings, then uses Linq to project each row into an anonymous object with properties for each column. The order of the properties in the object is the same as the order of the columns in the input CSV file.
Then, the code selects the columns to include and materializes the data into an array of arrays for writing out to the new CSV file. Finally, it writes the output array to a new CSV file using the File.WriteAllLines
method.
Note that this code assumes that the input CSV file and the output CSV file are UTF-8 encoded with no BOM. If your file encoding is different, you may need to specify the encoding in the File.ReadAllLines
and File.WriteAllLines
methods.
gistlibby LogSnag