C# Windows Forms OpenFileDialog Examples

Let us look at a simple C# Windows Forms OpenFileDialog example.

Example 1: OpenFileDialog

This example will comprise the following files:

  • OpenFileDialog.cs

Step 1: Create Project

  1. The first step is to create a C# Project.
  2. Go to FILE-->New-->Project to create a new project.

Step 2: Write Code

Write Code as follows:

*(a). OpenFileDialog.cs

Create a file named OpenFileDialog.cs

Here is the full code

using System;
using System.Windows.Forms;

namespace FolderBrowserDialogExample {
  class Form1 : Form {
    // The main entry point for the application.
    [STAThread]
    public static void Main() {
      Application.EnableVisualStyles();
      Application.Run(new Form1());
    }

    public Form1() {
      button.Text = "Open...";
      button.Location = new System.Drawing.Point(10, 10);
      button.Click += delegate(object sender, EventArgs e) {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
        System.Diagnostics.Debug.WriteLine(string.Format("dialog = {0}", openFileDialog));
        if (openFileDialog.ShowDialog() == DialogResult.OK)
          label.Text = string.Format("File = {0}", openFileDialog.FileName);
      };

      label.Text = "Path = ";
      label.Location = new System.Drawing.Point(10, 40);
      label.Width = 340;

      Text = "OpenFileDialog example";
      Controls.AddRange(new Control[] { button, label});
    }

    private Button button = new Button();
    private Label label = new Label();
  }
}

Run

Simply copy the source code into your C# Project,Build and Run. Alternatively download the code using the links provided below, then open the .csproj project, build and run.

Reference

Download the code using the below links:

Number Link
1. Download Example
2. Follow code author

Related Posts