See
csv file splited in more csv files
i need a console app to read a csv file and separate it into multiple files by n columns. For example i have a csv file with 7 columns and n =3. This means that the first file will have the first 3 columns of the original csv with the data from them, the second one will have the next 3 columns and data, and the third and last one will have the last column from the csv file and its data. it should work for multiple columns, not only 7
Thank you
Developer technologies | C#
2 answers
Sort by: Most helpful
-
Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
2022-01-26T15:31:58.537+00:00 -
Karen Payne MVP 35,586 Reputation points Volunteer Moderator
2022-01-26T17:06:04.353+00:00 See if this works for you, will need to change column names and perhaps use some assertions. Once executed there will be three files created in the executable folder.
Full source - while viewing the page, press . (a period) to open code in online version of VS Code.
- There are at least a handful of alternatives to this
- Does not cover selection of files
- No column validation
Model
namespace DelimitedDemo.Classes { public class SomeClass { public string Column1 { get; set; } public string Column2 { get; set; } public string Column3 { get; set; } public string Column4 { get; set; } public string Column5 { get; set; } public string Column6 { get; set; } public string Column7 { get; set; } public string Part1 => $"{Column1},{Column2},{Column3}"; public string Part2 => $"{Column4},{Column5},{Column6}"; public string Part3 => $"{Column7}"; } }
Worker class
using System; using System.IO; using System.Linq; namespace DelimitedDemo.Classes { public class Mocked { public static void ReadWrite(char delimitBy = ';') { var list = File.ReadAllLines( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt")) .Select((lineData) => { SomeClass someClass = new SomeClass(); // skip empty lines if (string.IsNullOrWhiteSpace(lineData)) return someClass; var lineArray = lineData.Split(delimitBy); someClass = new SomeClass { Column1 = lineArray[0], Column2 = lineArray[1], Column3 = lineArray[2], Column4 = lineArray[3], Column5 = lineArray[4], Column6 = lineArray[5], Column7 = lineArray[6] }; return someClass; }) // skip header .Skip(1) .ToList(); File.WriteAllLines("File1.txt", list.Select(x => x.Part1).ToArray()); File.WriteAllLines("File2.txt", list.Select(x => x.Part2).ToArray()); File.WriteAllLines("File3.txt", list.Select(x => x.Part3).ToArray()); } } }
Call the above
using System; using System.Windows.Forms; using DelimitedDemo.Classes; namespace DelimitedDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RunButton_Click(object sender, EventArgs e) { Mocked.ReadWrite(); } } }