Monday, October 1, 2012

Read and Write Text File Line by Line using c#


//Read and Write Text File Line by Line using c#
//TextBlock  property:
//AcceptsReturn :checked
//AcceptsTab: checked

//Add Reference

using Microsoft.Win32;

private void btnbrowse_Click(object sender, RoutedEventArgs e)
        {
            String AppPath = System.AppDomain.CurrentDomain.BaseDirectory;
            OpenFileDialog dlg = new OpenFileDialog() { DefaultExt = ".jpg" };
          

            dlg.Filter = "txt (.txt)|*.txt";
            dlg.ShowDialog();

            try
            {
                //if (System.IO.Directory.Exists(AppPath + "images") == false)
                //{
                //    System.IO.Directory.CreateDirectory(AppPath + "images");
                //}

                txtfile.Text = dlg.FileName.ToString();
                             

                //throw new Exception("");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            //btnNew.Visibility = Visibility.Hidden;
        }

        private void btnRead_Click(object sender, RoutedEventArgs e)
        {
            int counter = 0;
            string line;
            txt.Text = "";
            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(txtfile.Text);
            while ((line = file.ReadLine()) != null)
            {
                txt.Text = txt.Text + line +"\n";
                counter++;
            }

            file.Close();

        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            txt.Text = "";
        }

        private void btnWrite_Click(object sender, RoutedEventArgs e)
        {
          
            // Read the file and display it line by line.
            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(txtfile.Text);

                file.WriteLine(txt.Text);
                file.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
          
        }

0 comments: