Friday, February 10, 2012

Programmatically read and write a text file

The following is the source code for reading and writing a text file by C#

        void readData()
        {
             string filePath = Application.StartupPath + @"\data.txt";           
             if (File.Exists(filePath) == true)
            {
                StreamReader reader = new StreamReader(filePath);
                while (reader.EndOfStream == false)
                {
                    string line = reader.ReadLine();
                    if (string.IsNullOrEmpty(line)) continue;

                    Messagebox.Show(line);
                }
                reader.Close();
            }           
        }

        void writeData()
       {
            string filePath = Application.StartupPath + @"\data.txt";
            StreamWriter writer = new StreamWriter(filePath);                         
            string line = "This is a text file";
            writer.WriteLine(line);
           
            writer.Flush();
            writer.Close();

            MessageBox.Show("Saved");
       }

Hope this help!

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews