- This topic explains about the Working with OpenFileDialog Component in C#.
Working with OpenFileDialog Component in C#
- This OpenFiledialog presents users with a way to browse the folders of their computer or any computer on the network and allows them to open files.
- The dialog box returns the path and name of the file the user selected in the dialog box.
- First you have to add two controls from the ToolBox to the visual studio form that we opened.
1) Button Control
2) OpenFileDialog Control
Add below code inside the Button Click Event for working with OpenFileDialog component in C#
|
1 2 3 4 5 6 |
if (openFileDialog1.ShowDialog() == DialogResult.OK) { System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName); MessageBox.Show(sr.ReadToEnd()); sr.Close(); } |
- If you want to filter the file to open through the OpenFileDialog control in C#, do the following Code. (code shows only the files that we want to select)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Display an OpenFileDialog so the user can select a Cursor. { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Cursor Files|*.cur"; openFileDialog1.Title = "Select a Cursor File"; // Show the Dialog. // If the user clicked OK in the dialog and // a .CUR file was selected, open it. if (openFileDialog1.ShowDialog() == DialogResult.OK) { if (!string.IsNullOrEmpty(openFileDialog1.FileName)) { // Assign the cursor in the Stream to the Form's Cursor property. this.Cursor = new Cursor(openFileDialog1.OpenFile()); } } } |
Complete Code – Working with OpenFileDialog Component in C#
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace TestC { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // Display an OpenFileDialog so the user can select a Cursor. { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Cursor Files|*.cur"; openFileDialog1.Title = "Select a Cursor File"; // Show the Dialog. // If the user clicked OK in the dialog and // a .CUR file was selected, open it. if (openFileDialog1.ShowDialog() == DialogResult.OK) { if (!string.IsNullOrEmpty(openFileDialog1.FileName)) { // Assign the cursor in the Stream to the Form's Cursor property. this.Cursor = new Cursor(openFileDialog1.OpenFile()); } } } } } } |
Working with OpenFileDialog Component in C#






