reading from file


I'm quite new in c# programming and I have a little problem, I hope you'll help me. :)
I have a txt file that looks something like this:

123456 Ivan Losko
098765 Irene Kik
732647 Bilo Bilbilov

What I need to do is to read from this text file word by word. So I should use " " (space) as a separator so when I type 123456 in textBox1, Ivan Losko to appear in textBox2. ANy ideas?


  • in dotnet you will want to get your file into a StringReader.
    var dict = new Dictionary();
    var text = System.IO.File.ReadAllText("myfile.txt");
    var reader = new StringReader(text);
    var line = reader.ReadLine(); // gets the first line
    while (!string.IsNullOrEmpty(line))
    var data = line.Split(new[] {' '}, 2); // pick out the first 'word'
    dict.Add(data[0], data[1]); // 0 holds the id, 1 holds everything left
    // Do something
    line = reader.ReadLine(); // gets the next line

    var myTestResult = dict["123456"];
    // myTestResult will now have "Ivan Losko".

    as far as what to use for your field seperator is up to you. If you are dealing with user input, you might want to make sure that the user does not actually put that character into his/her input.

    string mySafeValue = userInput.Replace(" ", "");

    however, I think the trend these days is to write any kind of file output into XML because it is so easy to work with - but it adds alot of overhead to your data if your records are small.

    otherwise I would say you should stick this in a database.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion