I am attempting to read multiple CSV files in a directory, process and filter these appropriately based on a specific prefix using c#. I then want to write each row to a new CSV file that contains that prefix. The CSV header remains the same.
For example, I have a CSV file before processing as such:
If there is a prefix in a row starting with BAK as an example I want to extract all rows of data to a new CSV file that have that prefix, so my CSV would then look like this. Note that the prefix may not always be in the same place.
CSV after processing:
I have looked at other questions and answers and feel these do not address my question.
What I have so far (C#):
static void Main(string[] args) {
string sourceDirectory = @"C:\temp\csvfiles\";
var csvFiles = Directory.EnumerateFiles(sourceDirectory, "*.csv", SearchOption.AllDirectories);
foreach (string currentFile in csvFiles) {
//How do I read in only the specfic rows that I need containing certain prefixes
}
}
CodePudding user response:
You will need to read and parse each row of your input file and then inspect the data to determine if it should be written to the output file.
I don't know how much experience you have parsing CSV files though. There are many available that would make short work of this. May I recommend my own CsvParser?
CodePudding user response:
static void Main(string[] args)
{
string sourceDirectory = @"C:\temp\csvfiles\";
var csvFiles = Directory.EnumerateFiles(sourceDirectory, "*.csv", SearchOption.AllDirectories);
foreach (string currentFile in csvFiles)
{
//How do I read in only the specfic rows that I need containing certain prefixes
foreach (string line in File.ReadAllLines(currentFile).Where(m => m.Split(';').Last().Contains("BAK")))
{
Console.WriteLine(line);
}
}
}