Tuesday, June 17, 2014

Read Write Text Files





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO; //Add to work with fileSystem

namespace Read_Write_Text_Files
{
    ///Most of the classes you need to work with file system
    ///are in the 'System.IO' namespace. So you need to have
    ///using System.IO;
    ///
    ///In each reading from or writing to file, you need to
    ///have 3 steps:
    ///         1. Open file for either reading or writing
    ///         2. Either read or write
    ///         3. Close the file
    ///It is a good practice to always use a try catch finally
    ///just in case the file could not be created, could not
    ///be found or the device is not hooked up to your computer
    ///
    ///Use the File class. It includes methods to open a text
    ///file and return a StreamReader or StreamWriter object
    ///to allow you to read from or write to a text file

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            //create an open file dialog
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Filter = "txt files (*.txt)|*.txt|(*.cs)|*.cs";
            //display it
            DialogResult dr = fdlg.ShowDialog();
            if (dr == DialogResult.OK)
            {
                //get the selected file and display in the 
                //textbox (txtFilePath)
                txtFilePath.Text = fdlg.FileName;
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            StreamReader sr = null;
            try
            {
                //1. Open file for reading
                sr = File.OpenText(txtFilePath.Text);

                //2. Read it
                richTextBox2.Clear();
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    richTextBox2.AppendText(line + "\n");
                }
            }
            catch (ArgumentException ae)
            {
                MessageBox.Show(ae.Message);
            }
            catch (IOException ioe)
            {
                MessageBox.Show(ioe.Message);
            }
            finally
            {
                //3. close
                if (sr != null)
                    sr.Close();
            }
        }

        private void btnAverageGrade_Click(object sender, EventArgs e)
        {
            StreamReader sr = null;
            try
            {
                //1. Open file for reading
                sr = File.OpenText(txtFilePath.Text);

                //2. Read it
                richTextBox2.Clear();
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    richTextBox2.AppendText(line + "\n");

                    //1. Open file for reading
                    sr = File.OpenText(txtFilePath.Text);

                    //2. Read it

                    List<int> gradesList = new List<int>();

                    richTextBox2.Clear();
                    while (!sr.EndOfStream)
                    {
                        int grade = int.Parse(sr.ReadLine());
                        gradesList.Add(grade);
                        richTextBox2.AppendText(grade + "\n");
                    }
                    double avg = gradesList.Average();
                    richTextBox2.AppendText("\nAvg: " + avg.ToString("f1"));

                }

            }
            catch (FormatException fe)
            {
                MessageBox.Show(fe.Message, "Format Exception");
            }
            catch (ArgumentException ae)
            {
                MessageBox.Show(ae.Message);
            }
            catch (IOException ioe)
            {
                MessageBox.Show(ioe.Message);
            }
            finally
            {
                //3. close
                if (sr != null)
                    sr.Close();
            }
               
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            StreamWriter sw = null;
            try
            {
                //1. open file for appending
                sw = File.AppendText(txtFilePath.Text);
                //. Write to it
                string text = richTextBox1.Text;
                if (text != String.Empty)
                {
                    sw.WriteLine(text);
                    MessageBox.Show("Successfully saved to file");
                }
            }
            catch (ArgumentException ae)
            {
                MessageBox.Show(ae.Message);
            }
            catch (IOException ioe)
            {
                MessageBox.Show(ioe.Message);
            }
            finally
            {
                //3. close
                if (sw != null)
                    sw.Close();
            }
        }
    }
}
///Lab Assignment June 9th
///1. Open Notepad and enter 12 country names
///Write code to read the file content and load all the names
///into a list box.
///
///2. Open NotePad and enter 10 grades
///Write code to read this file and compute the average grade
///display all the grades and the average grade in a 
///richtextbox.
///
///=====================================================
///Lab Assignment "Du Jour"
///------------------------
///Create a class Account with fields
///_firstname, _lastname, _accountNumber, _balance
///
///Add the necessary constructor and properties
///as well as Deposit and Withdraw methods
///
///In Form1 Design a layout to allow a user to enter the Account Information and save to file 
///
///Add listview then read account file and populate a List<Account> (accountList), 
///as well as the listview

No comments:

Post a Comment