I'm new to C# and I'm having some trouble getting input from a file and using it properly.

I need to get input from a file and insert the values given into a function but the problem is I need to give the functions parameters that aren't strings.

TimePiece is the class I created. It take two ushort variables as the parameters.

const int NUM_TIMEPIECES = 15;
TimePiece[] T = new TimePiece[NUM_TIMEPIECES];
 try
        {
            using (StreamReader stream = new StreamReader("Times.txt"))
            {
                string line;
                line = stream.ReadToEnd();
                string[] lines = line.Split(' ');
                ushort j = 0;
                for (int i = 0; i < NUM_TIMEPIECES; ++i)
                {
                    T[i] = new TimePiece(Convert.ToUInt16(lines[j]), Convert.ToUInt16(lines[++j]));
                    ++j;
                }
            }
        }
        catch (Exception error)
        {
            Console.WriteLine("Error.");
            Console.WriteLine(error.Message);
        }
}

Input File text:
2400 1
1320 0
1259 0
0312 1
1527 1
0707 1
0033 0
1315 1
2222 0
1740 0
1645 1
0210 1
2342 1
1234 0
1652 0


I've tried various other methods to get this to work but it keeps giving me the error "Input string was not in correct format."

What am I doing wrong? And is there a better way to extract the data from the file and insert it into my function?

Thanks

You need to read a stream line by line or read all lines at once and split each line one after one.

string[] alllines = System.IO.File.ReadAllLines("times.txt");

        int val1 = 0, val2 = 0;
        int i = 0;
        foreach (string line in alllines)
        {
            string[] data = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

            if (data.Length == 2)
            {
                int.TryParse(data[0], out val1);
                int.TryParse(data[1], out val2);
                T[i] = new TimePiece(val1,val2);
                i++;
            }
        }

Thanks! Please mark this thread as solved if you have found an answer to your question and good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.