Dialogs in C# 101 – Opening and saving files

This tutorial will introduce you with the basics of using dialogs in C#.

These file operations are done using two classes:

  • OpenFileDialog – good for opening files using File Explorer dialog within the program
  • SaveFileDialog – good for saving files using File Explorer dialog within the program
Opening a file

To open a file, we will be using the OpenFileDialog class. This class allows you, as the programmer, to display a File Explorer dialog window. The user will be able to pick a file or multiple files and open them.

To open a file dialog in your program, you can use this snippet.

Let’s just briefly look at the code. The dialog variable represents an object of the OpenFileDialog class. The ShowDialog is a method that returns the dialog state after being closed. DialogResult is just an enumeration that represents each of the dialog states returned by the ShowDialog method. Then if the condition on the second line is true, our little program will display a MessageBox with the selected file’s path.

Saving file

To save a file, use this piece of code.

For the sake of demonstration, we created a variable dateAndTime that holds today’s date and current time. On the second line, we created an object of the SaveFileDialog class. In the if statement, we are checking if a directory and a file name is set. If that is true, then the current date and time is saved to a file.

Conslusion

The OpenFileDialog and SaveFileDialog classes are extremely powerful. In this part, we’ve shown how to open and close files using the File Explorer dialog window. In the next part, we will learn how to add file filters to the dialog.

Leave a Reply

Your email address will not be published. Required fields are marked *