TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# OpenFileDialog Example

Use the OpenFileDialog control in Windows Forms to enable the selection of a file.
OpenFileDialog. This allows users to browse folders and select files. It can be used with C# code. It displays the standard Windows dialog box. The results of the selection can be read in your C# code.SaveFileDialog
To begin developing your OpenFileDialog, you need to open your Windows Forms program in the Visual Studio designer and open the Toolbox pane. Find the OpenFileDialog entry and double-click on it.

Properties: With OpenFileDialog, you can only change properties in the Properties pane.

Start: Please select the openFileDialog1 icon in the tray at the bottom of the Visual Studio window, and then look at the Properties pane.

ShowDialog. You can open the OpenFileDialog that is in your Windows Forms program. The dialog will not open automatically and it must be invoked in your custom code. You will want to use an event handler to open the dialog in your C# code.

Here: We will use a button in this tutorial, which when clicked will open the dialog.

Button: You can add a Button control. Find the Button icon in the Toolbox and drag it to an area in your Windows Forms window.

Button

Also: You can add an event to the button click by double-clicking on the "button1" in the designer.

C# program that uses OpenFileDialog using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // Show the dialog and get result. DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) // Test result. { } Console.WriteLine(result); // <-- For debugging use. } } }
Notes, example. The code uses the openFileDialog1 component that was created in the designer in previous steps. The DialogResult enumerated type is assigned to the result of ShowDialog.

Then: This DialogResult variable is tested to see what action the user specified to take.

DialogResult

Tip: The actual strings from the dialog window can be accessed directly as properties on openFileDialog1.

Read files. You can access the file specified by the user in the OpenFileDialog—and then read it in using the System.IO namespace methods. We also handle exceptions, preventing some errors related to file system changes that are unavoidable.

Note: In this example, when you click on the button the dialog will ask you what file you want.

And: When you accept the dialog, the code will read in that file and print its size in bytes.

C# program that reads in file from OpenFileDialog using System; using System.IO; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int size = -1; DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog. if (result == DialogResult.OK) // Test result. { string file = openFileDialog1.FileName; try { string text = File.ReadAllText(file); size = text.Length; } catch (IOException) { } } Console.WriteLine(size); // <-- Shows file size in debugging mode. Console.WriteLine(result); // <-- For debugging use. } } }
Notes, click. The event handler is executed when the user clicks on the button1 control. An OpenFileDialog is displayed. Second, the DialogResult is tested. Next the FileName property is accessed and the file is read in with File.ReadAllText.File
Notes, tutorial. This tutorial could be continued with a TextBox or RichTextBox. We could display the file in a multiline text box. And SaveFileDialog could be used to persist user-generated changes.TextBoxRichTextBox
Properties. The OpenFileDialog control in Windows Forms has many properties that you can set directly in the designer. You do not need to assign them in your own C# code. This section shows some notes on these properties.

AddExtension: You can change this to False from its default True if you want to automatically fix file extension problems.

AutoUpgradeEnabled: This allows you to automatically get Vista-style open file dialogs. It is recommended.

DefaultExt: Set this to a string extension for files to automatically add that extension. This is not often useful.

DereferenceLinks: This tells Windows to resolve shortcuts (aliases) on the system before returning the paths.

FileName: You can initialize this in the designer to a preset file name. This is changed to be the name the user specifies.

InitialDirectory: Specify a string to use that folder as the starting point. Try using Environment.SpecialFolder with this property.

Environment

Multiselect: Specifies if multiple files can be selected at once in the dialog. Users can select multiple files by holding SHIFT or CTRL.

Filter. Filters make it easier for the user to open a valid file. The OpenFileDialog supports filters for matching file names. The asterisk indicates a wildcard. With an extension, you can filter by a file type.

Filter: Use this to specify the file matching filter for the dialog box. With "C# files|*.cs", only files ending with ".cs" are shown.

FilterIndex: Use to specify the default filter, which will have index of 1. The second filter if one exists would have index of 2.

ValidateNames: The Windows file system does not allow files to contain characters such as "*". This option should usually be left as True.

ReadOnly. To continue, the OpenFileDialog has some properties that allow users to specify whether a file should be read in read-only mode. The read-only checkbox can be displayed. Usually these are not needed.

ReadOnlyChecked: This changes the default value of the "read only" checkbox, which is only shown when "ShowReadOnly" is set to True.

ShowReadOnly: Whether you want the read-only checkbox to be shown. If set to True, change "ReadOnlyChecked" to set the check state.

Summary. We looked at the useful OpenFileDialog in Windows Forms. Nearly every nontrivial program will need to have an open file dialog. This control implements this functionality without any problems.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf