I have a csv parsing method in my Windows App that reads headers and information from the subsequent lines. I am not sure if I am doing in an efficient way. Please comment.
public List<(string IPN, string FPTech)> GetIPNFPTechFromCSV(string filePath)
{
List<(string, string)> IPNFPTechPairs = new List<(string, string)>();
using (StreamReader csvfileReader = new StreamReader(filePath))
{
List<string> headings = new List<string>();
if (HasHeaderRow)
{
headings = LoadFieldNamesFromHeaderRow(csvfileReader.ReadLine());
if (headings.Count != 2)
return null;
else
{
int IPNPos = headings.IndexOf("PartNumber");
int FPPos = headings.IndexOf("FPTech");
if (IPNPos != -1 && FPPos != -1)
{
string line;
while ((line = csvfileReader.ReadLine()) != null)
{
var IPNFPTechPair = (IPN: line.Split(Delimiter)[IPNPos], FPTech: line.Split(Delimiter)[FPPos]);
IPNFPTechPairs.Add(IPNFPTechPair);
}
}
else
return null;
}
}
else
return null;
}
return IPNFPTechPairs;
}
In the caller I am doing
var InputPairs = inputcsvfile.GetIPNFPTechFromCSV(txt_filePath.Text);
if (InputPairs == null)
{
MessageBox.Show("Please make sure input file is in valid format with PartNumber,FPTech Headers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
To me, it looks like I am returning nulls from too many paths in my csv parsing method. Please let me know how can I improve this code. I am also not sure how do we efficiently log or report eceptions though out the Windows App. Any ideas are welcome please.
Sample Input CSV File
FPTech,PartNumber
TK0,H19873-001
TK1,H19873-001
TK2,H19872-001
TK1,H19874-001
TK0,H19872-001
The input .csv should be in this format and the FPTech and PartNumber Headers can interchange and sometime smissing. When missing, any of these I want to report to user.