Pages

Tuesday, 6 May 2014

File Read and Write in C#


Hi,

Here you are gonna learn File Read and Write in C#.

The below project deals with;
    a) Getting data (2 names) from the
        user.
    b) Write the data into a text file.
    c) Reading the data from the text file
        and displaying it.

so let's start


Steps

1. Open Visual Studio -> New Project -> Windows Form Application with name
    FileReadWrite

2. Now add Buttons, Labels and Textboxes to your empty Form and design it as shown in 
    the below screenshot



3. Also change the Name and Text of the controls added from the Properties dialog box.

     Name         Text
     btnClear      Clear
     btnOpen      Open
     btnSave       Save
     txtName1
     txtName2

4. Now double click on Clear  button and copy the below code;

       //Clear text in both the textboxes
            txtName1.Text = "";
            txtName2.Text = "";

5. Now double click on Open  button and copy the below code;

             //Calling the OpenFile() function
            OpenFile();
            //Show data from list to textbox
            if (Namelist.Count > 0)
            {
                txtName1.Text = Namelist[0];
                txtName2.Text = Namelist[1];
            }

6. Now double click on Save  button and copy the below code;

            //Check if both textboxes are not empty
            if (txtName1.Text.Length > 0 && txtName2.Text.Length > 0)
            {

                Namelist.Clear();
                Namelist.Add(txtName1.Text);
                Namelist.Add(txtName2.Text);
                //Calling the SaveFile() function
                SaveFile();
                MessageBox.Show("Saved");
            }

7. Now update your Form1.cs with the below given code;

    Form1.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace FileReadWrite
{
    public partial class Form1 : Form
    {
        //File Path to save the data
        string FileName = Path.Combine(Application.StartupPath,"Data.txt");
        //String List to hold the data to be saved
        List<string> Namelist = new List<string>();
        public Form1()
        {
            InitializeComponent();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
           //Clear text in both the textboxes
            txtName1.Text = "";
            txtName2.Text = "";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            //Check if both textboxes are not empty
            if (txtName1.Text.Length > 0 && txtName2.Text.Length > 0)
            {

                Namelist.Clear();
                Namelist.Add(txtName1.Text);
                Namelist.Add(txtName2.Text);
                //Calling the SaveFile() function
                SaveFile();
                MessageBox.Show("Saved");
            }
        }
      
        private void btnOpen_Click(object sender, EventArgs e)
        {
            //Calling the OpenFile() function
            OpenFile();
            //Show data from list to textbox
            if (Namelist.Count > 0)
            {
                txtName1.Text = Namelist[0];
                txtName2.Text = Namelist[1];
            }
        }
        void SaveFile()
        {
            //Write data to file
            using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                StreamWriter sr = new StreamWriter(fs);
                foreach (String data in Namelist)
                {
                    sr.WriteLine(data);
                }
                sr.Close();

            }

        }
        void OpenFile()
        {
            if (File.Exists(FileName))
            {
                Namelist.Clear();
                //Open data from file
                using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    String line = "";
                    StreamReader sr = new StreamReader(fs);
                    while ((line = sr.ReadLine()) != null)
                    {
                        Namelist.Add(line);
                    }
                    sr.Close();
                }
            }
        }
    }
}

7. Now Run your project and input the names in the textboxes, click on Save. Explore the
    Application path of your project, there will be a file named Data.txt in which you 
    save the names(See the screenshot below). 



8. Now Clear  the names and click on Open, the names will be reloaded from the textfile
    Data.txt.


Output


Conclusion

So you have learned to Read and Write Files in C#. In case of any doubts / errors, please drop in a comment.

See Also


No comments:

Post a Comment

 

About Me

I am Tijo Tom, a Computer Engineer from India.Right from my schooling, I had a passion for Programming, PC Tricks, Virus Creation and Hacking.

I started this blog on Jan 1, 2014 to share my views and ideas with the world.

You can know more about me on