Question Creating text files

neilyd

New member
Joined
Feb 9, 2016
Messages
3
Programming Experience
Beginner
            decimal speed, distance;
            int hours;
            int count = 1;
            StreamWriter outputfile;
            if (decimal.TryParse(textBox1.Text, out speed))
            {
                if (int.TryParse(textBox2.Text, out hours))
                {
                    while (count <= hours)
                    {


                        distance = speed * count;
                        outputfile = File.CreateText("Distance.txt");
                        outputfile.WriteLine("After hour " + count + " the distance is " + distance.ToString());
                        outputfile.Close();
                        MessageBox.Show("The distance was counted.");
                        count = count + 1;
                    }
                }
            }

In the text files it shows only the one line . for example , if i enter 40(speed) and 3(hour) : After hour 3 the distance is 120. But i want it to show each hour. like hour 1 hour 2 hour 3. soo whats wrong here
 
Last edited by a moderator:
File.CreateText Method (String) (System.IO)
If the file specified by path does not exist, it is created. If the file does exist, its contents are overwritten.
File.AppendText Method (String) (System.IO)
If the file specified by path does not exist, it is created. If the file does exist, write operations to the StreamWriter append text to the file.
Also you don't need to open/create file in every loop iteration, you can to this before the loop, and use the returned StreamWriter for write operation within the loop.
Return Value
Type: System.IO.StreamWriter
 
Back
Top Bottom