C# File Handling with Dialogs


Introduction

File data needs to be processed in nearly every non-trivial program, and the classes in the base class library that you can use have lots of details. With these benchmarks and examples focused on file IO in the C# language, we evaluate file handling.

Dialog boxes are used to gather input from users. You can create your own dialog boxes or use the built-in dialog boxes.

Dialogs

  • OpenFileDialog
  • SaveFileDialog
  • FolderBrowserDialog
  • FontDialog
  • ColorDialog

Design

In the design form section ,drag 'n drop dialogs, a richtextbox and five button control as show below:

1.gif

Program

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace filehanding
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
              StreamReader sr = new StreamReader(openFileDialog1.FileName);
              richTextBox1.Text=sr.ReadToEnd();
              sr.Close();
            }
       }       
        private void button3_Click(object sender, EventArgs e)
        {
            FontDialog font = new FontDialog();
            if (font.ShowDialog() != DialogResult.Cancel)
            {
               richTextBox1.Font = font.Font;           
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (colorDialog1.ShowDialog() != DialogResult.Cancel)
            {
                richTextBox1.ForeColor = colorDialog1.Color;
            }
        }
        private void button2_Click_1(object sender, EventArgs e)
        {
            //saveFileDialog1.Filter = "txt files (*.txt)|*.txt";
            saveFileDialog1.Filter = "txt files (*.doc)|*.doc";
           if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && saveFileDialog1.FileName.Length > 0)
            {
                 richTextBox1.SaveFile(saveFileDialog1.FileName,RichTextBoxStreamType.PlainText);
            }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Text = folderBrowserDialog1.SelectedPath;
            }
 
        }
    }
}

Output: To Run hit F5.

Open file Button


2.gif

Result

3.gif

Save file Button

4.gif 

Browse folder Button

browse-1.gif

Result


r-browse.gif

Font Change Button

5.gif

Result


6.gif

Change Color Button

Untitled-7.gif

Result


8.gif