There is a file with the following contents:

Tr_RouteFile (RouteID (USA1) Name ("Northeast Corridor")

and such code:

string[] dirroutes = new DirectoryInfo("D:\\games\\train simulator\\routes").GetFiles("*.trk",SearchOption.AllDirectories).Select(f => f.Name).ToArray(); foreach (string s in dirroutes) { metroComboBox1.Items.Add(s); } 

need Name("Northeast Corridor") from file to be added to metroComboBox1 , how to do it?

  • 3
    You will have to parse the string contained in the file. To do this, you must first come up with a grammar (that is, describe what can and can not be in this file itself). - VladD

2 answers 2

Cut unnecessary.

 string[] dirroutes = new DirectoryInfo("D:\\games\\train simulator\\routes").GetFiles("*.trk", SearchOption.AllDirectories).Select(f => f.Name).ToArray(); foreach (string s in dirroutes) { metroComboBox1.Items.Add(s.Remove(0, s.IndexOf("Name"))); } 

if you mean not the name of the file and the file is ONLY the text that is described in the topic start.

 string[] dirroutes = new DirectoryInfo("D:\\games\\train simulator\\routes").GetFiles("*.trk", SearchOption.AllDirectories).Select(f => f.Name).ToArray(); foreach (string s in dirroutes) { string line=System.IO.File.ReadAllText(s); metroComboBox1.Items.Add(line.Substring(line.IndexOf("Name") + 8, line.LastIndexOf(" )") - line.IndexOf("Name") - 9)); } 

also in both conditions, before parsing lines, it would be nice to add the condition if (line.IndexOf ("Name")> 0)

  • I correctly understood that you want a Name ("Northeast Corridor")? Or just that in quotes - xSx
  • s.Substring (s.IndexOf ("Name") + 8, s.LastIndexOf (")") - s.IndexOf ("Name") - 9): D well, you can make it more beautiful) - xSx
  • ComboBox1.Items.Add (s.Substring (s.IndexOf ("Name") + 8, s.LastIndexOf (")") - s.IndexOf ("Name") - 9)); gives an error what am i doing netak? - SergXcom
  • hmm So this is what we are trying to take from the file name, did you mean the contents of the file? Then I will complement the answer. You should read the inside of File.ReadAllText (S) and this line is already manner described above - xSx
  • supplemented the answer. It's just not clear, then why did you even try to cram the name of the file into the combo box, if you need insides? Moreover, it was better to take the directory files and run through them, rather than make an array of strings ... - xSx

Well, if the name is always in the quotes, then let the program understand that from the resulting string you need to take the text only between the quotes. although it is easier to remove everything from the beginning to the first quote and from the second to the end.

  • How to implement this in code? - SergXcom