Search This Blog

Thursday, September 16, 2010

reading & writing a text file in c#.net



using System;
using System.Data;
using System.Windows.Forms;
using System.IO;

namespace textpad
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void open_btn_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "text|*.txt|documents|*.doc|AllFiles|*.*";
            DialogResult res=openFileDialog1.ShowDialog();
            if (res == DialogResult.OK)
            {
                FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                string s, str = null;
                s = sr.ReadLine();

                while (s != null)
                {
                    str = str + s + Convert.ToChar(13) + Convert.ToChar(10);
                    s = sr.ReadLine();
                }

                textBox1.Text = str;
                sr.Close();
                fs.Close();
            }        
        }

        private void save_btn_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "text files|*.txt|documents|*.doc|AllFiles|*.*";
            DialogResult res=saveFileDialog1.ShowDialog();
            if (res == DialogResult.OK)
            {
                FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(textBox1.Text);
                sw.Close();
                fs.Close();
            }
        }

        private void clear_btn_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

        private void exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
 
    }
}