Search code examples
c#splittext-filesstreamreader

Returning values from text file : C#


I have a .txt file that contains information about vehicles that I add via another project. I want to read the text file, retrieve each VIN number, and place just the actual number itself in a combo box when the form is loaded. The info for each vehicle in the txt file looks like:

Model: 'model'

Manufacturer: 'manufacturer'

VIN Number: 'VIN number'

This is what I have:

using (StreamReader reader = new StreamReader(@"D:\carCenter\carCenter\bin\Debug\Vehicles.txt"))
        {
            string[] lines = File.ReadAllLines(@"D:\carCenter\carCenter\bin\Debug\Vehicles.txt");
            foreach(string line in lines)
            {
                if (line.Contains("VIN"))
                {
                    Char colon = ':';
                    string[] vins = line.Split(new string[] {"VIN Number: "}, StringSplitOptions.None);

                    for (int i = 0; i < 1; i++)
                    {
                        foreach(var vin in vins)
                        {
                            vinComboBox.Items.Add(vins[i]);
                        }

                    }

                }
            }

Solution

  • One solution is to have a general purpose function like this:

    private String GetDataToRightOfLastColon(String line)
    {
      line = line.Trim();
    
      var indexOfLastColon = line.LastIndexOf(':');
    
      /* If line does not contain a ':' character,
         or ':' is the last non-space character in line,
         throw an exception. */
      if ((indexOfLastColon == -1) || (indexOfLastColon == (line.Length - 1)))
        throw new ArgumentException(
          String.Format("The line '{0}' does not have the correct format.", line));
    
      return line.Substring(indexOfLastColon + 1).Trim();
    }
    

    Next, apply that function via LINQ to process the text file and populate the combobox:

    vinComboBox.Items.AddRange(
      File
      .ReadAllLines(@"D:\carCenter\carCenter\bin\Debug\Vehicles.txt")
      .Where(line => line.Trim().StartsWith("VIN"))
      .Select(line => GetDataToRightOfLastColon(line))
      .ToArray()
    );