Search code examples
c#openfiledialog

c# Reading a text file using OpenFileDialog and then make the average


I need to make this :

Make a Windows program to read numbers from a file with a box OpenFileDialog dialog. The program must find the average of the numbers and show it to display a text box.

I only open the file and i show it in the textbox but, i don't know how i can calculate the average from the file, i tried put the file content into array and then make the operation but don't works.

private void OpenFile_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "File text(*.txt)|*.txt|File jgp (*.jpg)|*.jpg|All files (*.*)|*.*";
    if (ofd.ShowDialog() == DialogResult.OK)

    {
        FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
        StreamReader sr = new StreamReader(fs);
        string cad = sr.ReadToEnd();

        txt1.Text = cad;

        sr.Close();
        fs.Close();
        fs.Dispose();
    }
}

private void Average_Click(object sender, EventArgs e)
{
    string res = txt1.Text;            
    mitja.Text = res;
}

Solution

  • cad.Split(Environment.NewLine).Select(a => Convert.ToInt32(a)).Average(a => a);