I'm writing an automation program to parse a tab-delimited file and write the data into another program. Currently it takes each line of the file, splits it by tab, and uses the different entries in it's commands. My issues is that even though all the data entries I am parsing should have 'X' amount of fields, there are a good number of fields that are just empty, and sometimes there are tabs that will immediately succeed other tabs.
When I try and access the list of strings from the split file-line, I find myself sometimes getting an IndexOutOfRangeException quite frequently. Would the multiple tabs be causing my list to not always end up with 'X' amount of fields, and therefore throw this exception? If so, is there a way around this?
[EDIT] Heres the code:
string[] parts = line.Split('\t');
String Organization = parts[0];
String SalesRep_FirstName = SalesRep.Split(' ').First();
String SalesRep_LastName = SalesRep.Split(' ').Last();
String Opportunity = parts[1] == "" ? "" : parts[1];
String Type = parts[6] == "" ? comboBox1.SelectedItem.ToString() : parts[6];
String CloseMonth = (parts[5].Split('/'))[0] == "" ? "12" : (parts[5].Split('/'))[0];
String CloseDay = (parts[5].Split('/'))[1] == "" ? "21" : (parts[5].Split('/'))[1];
String CloseYear = (parts[5].Split('/'))[2] == "" ? "2012" : (parts[5].Split('/'))[2];
String Stage = (parts[2].Split('-'))[0] == "" ? "1" : (parts[2].Split('-'))[0];
String Probability = parts[4] == "" ? "0" : (Math.Round(decimal.Parse(parts[4]) / 10) * 10).ToString();
String Source = parts[7] == "" ? "" : parts[7];
String Department = Type;
String Product = Opportunity;
String Revenue = parts[3] == "" ? "" : parts[3];
Ideally, each instance of the list parts will have 9 entries, (parts[8] is redundant, so its not referenced here)
You can split a string in two ways:
string input = "x\t\ty\t\t\tz";
char[] separator = new char[] { '\t' };
string[] result1 = input.Split(separator, StringSplitOptions.None);
// result1 == new string[] { "x", "", "y", "", "", "z" }
string[] result2 = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
// result2 == new string[] { "x", "y", "z" }
If you're using StringSplitOptions.None, then the resulting array should always have the same length -- provided that each input contains the same number of tabs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With