-2

I have a text file that has three columns primarily. In some rows there are only two columns with data. I extract the file content into an array of strings.

I print txttxtOUIsearchResults.AppendText(t[0] + " - " + t[2] + Environment.NewLine); with no issue. However, if the string array has only t[0] and t[1], I will get an exception.

Is there a way to test if the array contains three strings and to do something else rather than throwing an exception if it doesn't?

// Search results from the list.
List<string> SearchResults = texter.FindAll(o => o.StartsWith(strExpand));
// The foreach will locate multiple lines if it exist within the text file.
foreach (string value in SearchResults)
{

    var t = value.Split('\t'); // 3 string arrays.

    var CkEmpty = t[2]; // Just one of 20 things I test that don't work.

    if (String.IsNullOrEmpty(CkEmpty)) // However, sometimes there's only two string arrays. If only two then it will error.
    {
        // Permit the textbox control to run in a thread.
        txttxtOUIsearchResults.Invoke((Action)delegate
        {
            txttxtOUIsearchResults.AppendText(t[0] + " - " + t[1] + Environment.NewLine);
        });
    }
    else
    {
        // Permit the textbox control to run in a thread.
        txttxtOUIsearchResults.Invoke((Action)delegate
        {
            txttxtOUIsearchResults.AppendText(t[0] + " - " + t[2] + Environment.NewLine);
        });
    }
}
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
DemarcPoint
  • 183
  • 1
  • 9

1 Answers1

0

Looks like you always want the first and the last value in your string, regardles if there are 2 or 3 values. So:

 // Search results from the list.
 List<string> SearchResults = texter.FindAll(o => o.StartsWith(strExpand));
 // The foreach will locate multiple lines if it exist within the text file.
 foreach (string value in SearchResults)
 {
 
     var t = value.Split('\t'); // 2-3 string arrays.

     txttxtOUIsearchResults.Invoke((Action)delegate
         {
             txttxtOUIsearchResults.AppendText(t[0] + " - " + t[t.Length - 1] + Environment.NewLine);
         });
 }
Jonathan
  • 4,916
  • 2
  • 20
  • 37