Click to See Complete Forum and Search --> : Reading a specific line from txt file


Dumpen
March 23rd, 2008, 10:54 AM
Hello.

I have a text file that looks like this:
0 1 "Bull Fighter" 6 100 0 16 20 6 0 28 6 3 0 1 5 400 1600 10 2 130 10 6 0 0 0 0 0
1 1 "Hound" 9 140 0 22 27 9 0 39 9 3 0 1 5 400 1600 10 2 130 10 6 0 0 0 0 0
2 1 "Budge Dragon" 4 60 0 10 13 3 0 18 3 3 0 1 4 400 2000 10 2 120 10 6 0 0 0 0 0
3 1 "Spider" 2 30 0 4 7 1 0 8 1 2 0 1 5 400 1800 10 2 120 10 6 0 0 0 0 0

It is called monster.txt

The first value is a id which I also use in my script.

Lets say I have the id 3, this would be "Spider" since the first number of "Spider" is 3

What is the best way to read the monster.txt file for the id and retrive the name? (Name = "Spider", id = 3) (As my example above)

EDIT:
I just used

private void findMonster(int monsterId)
{
StreamReader sr = new StreamReader(@monsterLocation);
int searchId = monsterId;
int actualId = 0;
string name = "(Not found)";
string[] details = null;
string line = null;
while ((line = sr.ReadLine()) != null)
{
line = line.Trim();
if (line == "") continue;
details = line.Split('\t');
actualId = int.Parse(details[0]);
if (actualId == searchId)
{
name = details[2].Replace("\"", "");
break;
}
}
sr.Close();
txtMonster.Text = name;
}

Dont know if its the best way, but it works..

nelo
March 23rd, 2008, 03:54 PM
Do you have any control over the format of the file? If you do I would recommend using XML format. Ultimately because it is a text file the whole file is loaded into memory (as far as I know). The advantage of using an XML file is that the System.Xml namespace has some classes that would enable you to search for a particular piece of information from a file. But if you haven't got any control over the format of your monster file or you don't want to learn XML I think your approach is the best way.

angedelamort
March 24th, 2008, 12:40 PM
If you want really fast access, without doing IO operation all the time (like you do in your solution), I would suggest that you parse only your file once and put it in a dictionary or a similar structure optimized for search. Since you probably doesn't have a lot of data, it can probably stay in memory with no problems.

Nelo suggested to use XML. I think it's a nice idea. Not for searching, but it's more robust than just using 'tabs' and 'return' in a text file and can be automatically parsed into your C# structure without doing any code.