Tuesday, 3 September 2013

Reading from a textfile to retrieve values using C# in Microsoft Virtual Studio 2012

Reading from a textfile to retrieve values using C# in Microsoft Virtual
Studio 2012

Use Notepad to place the following values in a text file: 86, 97, 144,
26.To simplify the problem, the values can each be placed on separate
lines.Write a C# program to retrieve the values from the text file and
print the average of the values, formatted with two decimal places.
However, I keep getting error messages when I compile my code. I have
listed my code below for you to view, and to offer me any feedback on what
to do to correct my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ReadTextFileApp
{
public class ReadTextFileApp : System.Windows.Forms.Form
{
public ReadTextFileApp()
{
InitializeComponent();
}
private void ReadTextFileApp_Load(object sender, EventArgs e)
{
string inValue;
string data;
inFile = new StreamReader("name.txt", true);
}
private void btnDisplayValues_Click(object sender, EventArgs e)
{
string inValue;
int count = 0;
int total = 0;
this.lblDisp.Text = "";
if(File.Exists("name.txt"))
{
try
{
inFile = new StreamReader{"name.txt");
while ((inValue = inFile.ReadLine()) |= null)
{
count++;
this.lblDisp.Text += " " + inValue;
total += int.Parse(inValue);
}
average = (double)
total / count;
}
catch(System.IO.IOException exc)
{
this.lblDisp.Text = exc.Message;
}
}
else
{
this.lblDisp.Text = "File Unavailable";
}
this.lblDisp.Visible = true;
{
private void ReadTextFileApp_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
try
{
inFile.Close();
}
catch
{
}
}
private void btnCalcDispAve_Click(object sender, EventArgs e)
{
this.lblAve.Text = "";
this.lblAve.Text = " " + average.ToString();
this.lblAve.Visible = true;
}
}
}

No comments:

Post a Comment