Wednesday, March 9, 2011

Browse and Display Text File (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;          //namespace buat OpenFileDialog 
using System.IO;

namespace BrowseAndDisplay
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        private void buttonClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void buttonBrowse_Click(object sender, RoutedEventArgs e)
        {
            //create an instance of the open file dialog box
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = "C:";
            openFileDialog.Title = "Choose one of the text file";
            openFileDialog.FileName = "";
            openFileDialog.Filter = "Text file|*.txt";

            openFileDialog.ShowDialog();

            //isi textBox FileLocation dengan path file yang akan dibuka
            textBoxFileLocation.Text = openFileDialog.FileName;

            //tampilkan isi file text ke textBox DisplayTextFile
            FileInfo src = new FileInfo(openFileDialog.FileName);

            textBoxDisplayTextFile.Text = "";
            TextReader reader = src.OpenText();
            string line = reader.ReadLine();

            while (line != null)
            {
                textBoxDisplayTextFile.Text += line + '\n';
                line = reader.ReadLine();
            }
            reader.Close();
        }
    }
}



    
        
            
            
        
        

No comments:

Post a Comment