views:

168

answers:

2

Basically I need someone to help me or show me the code that will allow me to read a name and a price from a file i have called c1.txt.

This is what i already have.

    TextReader c1 = new StreamReader("c1.txt");
        if (cse == "c1")
        {
            string compc1;
            compc1 = c1.ReadLine();
            Console.WriteLine(compc1);
            Console.WriteLine();
            compcase = compc1;
            compcasecost = 89.99;
        }

also how to select a line to read from a text document would be great.

+10  A: 

You haven't told us the format of the text file. I am going to assume the following:

Milk|2.69
Eggs|1.79
Yogurt|2.99
Soy milk|3.79

You also didn't specify the output. I am going to assume the following:

Name = Milk, Price = 2.69
Name = Eggs, Price = 1.79
Name = Yogurt, Price = 2.99
Name = Soy milk, Price = 3.79

Then the following will read such a file and produce the desired output.

using(TextReader tr = new StreamReader("c1.txt")) {
    string line;
    while((line = tr.ReadLine()) != null) {
        string[] fields = line.Split('|');
        string name = fields[0];
        decimal price = Decimal.Parse(fields[1]);
        Console.WriteLine(
            String.Format("Name = {0}, Price = {1}", name, price)
        );
    }
}

If your separator is different then you need to change the parameter '|' to the method String.Split (invoked on the instance of String named line as line.Split('|')).

If your format needs to be different then you need to play with the line

String.Format("Name = {0}, Price = {1}", name, price)

Let me know if you have any questions.

Jason
A: 
    static void ReadText()
    {
        //Open the file, read it, put each line in an array of strings and then close the file
        string[] text = File.ReadAllLines("c1.txt");

        //Use StringBuilder instead of string to optimize performance
        StringBuilder name = null;
        StringBuilder price = null;
        foreach (string line in text)
        {
            // Get the name of the product (the string before the separator "," )
            name = new StringBuilder((line.Split(','))[0]);
            //Get the Price (the string after the separator "," )
            price = new StringBuilder((line.Split(','))[1]);

            //Format & Display the result in the Console
            Console.WriteLine("Name = {0}, Price = {1}", name, price);
        }

It gives the same results as @Jason's method, but I think this is an optimized version.

iChaib
What is the optimization in creating a StringBuilder on a string that you're not manipulating at all, and doing the split operation twice instead of once? You usually only create StringBuilder reduce the cost of multiple appends. And you already get two perfectly good strings in the array returned by line.Split.
JasonTrue
Further, this reads the file into memory all at once which could also create issues (time to read plus potential memory issues).
Jason