Последнее обновление: 31.10.2015
Окна открытия и сохранения файла представлены классами OpenFileDialog и SaveFileDialog.
Они имеют во многом схожую функциональность, поэтому рассмотрим их вместе.
OpenFileDialog и SaveFileDialog имеют ряд общих свойств, среди которых можно выделить следующие:
-
DefaultExt: устанавливает расширение файла, которое добавляется по умолчанию, если пользователь ввел имя файла без расширения -
AddExtension: при значенииtrueдобавляет к имени файла расширение при его отсуствии. Расширение берется из
свойстваDefaultExtилиFilter -
CheckFileExists: если имеет значениеtrue, то проверяет существование файла с указанным именем -
CheckPathExists: если имеет значениеtrue, то проверяет существование пути к файлу с указанным именем -
FileName: возвращает полное имя файла, выбранного в диалоговом окне -
Filter: задает фильтр файлов, благодаря чему в диалоговом окне можно отфильтровать файлы по расширению. Фильтр задается в следующем формате
Название_файлов|*.расширение. Например,Текстовые файлы(*.txt)|*.txt. Можно задать сразу несколько фильтров, для этого они разделяются
вертикальной линией |. Например,Bitmap files (*.bmp)|*.bmp|Image files (*.jpg)|*.jpg -
InitialDirectory: устанавливает каталог, который отображается при первом вызове окна -
Title: заголовок диалогового окна
Отдельно у класса SaveFileDialog можно еще выделить пару свойств:
-
CreatePrompt: при значенииtrueв случае, если указан не существующий файл, то будет отображаться сообщение о его создании -
OverwritePrompt: при значенииtrueв случае, если указан существующий файл, то будет отображаться сообщение о том, что файл будет перезаписан
Чтобы отобразить диалоговое окно, надо вызвать метод ShowDialog().
Рассмотрим оба диалоговых окна на примере. Добавим на форму текстовое поле textBox1 и две кнопки button1 и button2. Также перетащим с панели инструментов
компоненты OpenFileDialog и SaveFileDialog. После добавления они отобразятся внизу дизайнера формы. В итоге форма будет выглядеть примерно так:
Теперь изменим код формы:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += button1_Click;
button2.Click += button2_Click;
openFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";
saveFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";
}
// сохранение файла
void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
return;
// получаем выбранный файл
string filename = saveFileDialog1.FileName;
// сохраняем текст в файл
System.IO.File.WriteAllText(filename, textBox1.Text);
MessageBox.Show("Файл сохранен");
}
// открытие файла
void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
return;
// получаем выбранный файл
string filename = openFileDialog1.FileName;
// читаем файл в строку
string fileText = System.IO.File.ReadAllText(filename);
textBox1.Text = fileText;
MessageBox.Show("Файл открыт");
}
}
По нажатию на первую кнопку будет открываться окно открытия файла. После выбора файла он будет считываться, а его текст будет отображаться в
текстовом поле. Клик на вторую кнопку отобразит окно для сохранения файла, в котором надо установить его название. И после этого произойдет сохранение
текста из текстового поля в файл.
When developing projects in Winforms, there will come a time when you will have to deal with Browser Folder and Open File Dialogs. This article will show you how to accomplish common tasks using those two controls in Windows Forms using C#.
As the name suggests, with BrowserFolderDialog control, we select folders and with OpenFileDialog, we select files as shown below:
Here are the most common tasks, when dealing with folder and file dialogs:
How to create Folder Browser Dialog?
string folderpath = "";
FolderBrowserDialog fbd=new FolderBrowserDialog();
DialogResult dr=fbd.ShowDialog();
if (dr == DialogResult.OK)
{
folderpath=fbd.SelectedPath;
}
if (folderpath!="")
...
string filename = "";
OpenFileDialog ofd = new OpenFileDialog();
DialogResult dr=ofd.ShowDialog();
if (dr == DialogResult.OK)
{
filename = ofd.FileName;
}
if (filename!="")
...
How to make Open File Dialog to show only files with specific extensions?
For that we use Filters property. Each option contains the description and the filter pattern which is separated by a vertical line |. You can add multiple options which are also separated by a vertical line.
ofd.Filter = "Image Files|*.BMP;*.GIF;*.JPG;*.JPEG;*.PNG|All files (*.*)|*.*"
To set which options will be the default, we use FilterIndex property. First Entry always starts with 1 and not 0. With the above example, we would set Index to 2 for «All files«.
//To set default to "All files", set the property to 2
ofd.FilterIndex = 2;
How to make Open File Dialog to open in a specific folder?
ofd.InitialDirectory = "c:\\temp";
How to make Open File Dialog to allow the selection of multiple files?
We set MultiSelect property to true and use Filenames property instead of Filename to retrieve a list of selected files.
string[] filenames = {};
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
DialogResult dr=ofd.ShowDialog();
if (dr == DialogResult.OK)
{
filenames = ofd.FileNames;
}
I hope you found this article helpful. This article covered only the most basic uses. If you think there is some important task that should be mentioned regarding file browser or folder browser dialog, let me know in the comment section and I might add the task in the future update.
In a WinForms project, you can prompt the user to select a file by using the OpenFileDialog control:
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = openFileDialog.FileName;
}
Code language: C# (cs)
When you call ShowDialog(), it’ll prompt the user to select a file:
When the user clicks Open, you’ll be able to get the file path they selected from the OpenFileDialog.FileName property.
To use the OpenFileDialog control, drag it from the toolbox to the form. Then you can modify the properties through the UI or programmatically (as I’ll show in examples in this article).
The most important properties are InitialDirectory, Filter, and Multiselect. InitialDirectory is straightforward: when the prompt opens, it’ll open up to the specified initial directory. In this article, I’ll go into details about Filter and Multiselect properties, and then show an example of displaying the selected file’s metadata and content.
Filter which files can be selected
The Filter property controls which files appear in the prompt.
Here’s an example that only lets the user select .config and .json files:
openFileDialog.Filter = "Configuration files|*.config;*.json";
Code language: C# (cs)
Only .config and .json files will appear:
Filter string format
The filter string format is like this: <file group 1 name>|<file 1 name>;<file 2 name>|<file group 2 name>|<file 1 name><file 2 name>. This is a pretty confusing format, so it’s easier to just show examples.
Example – Only show a specific file
The following only allows the user to select a file with the name appsettings.json:
openFileDialog.Filter = "appsettings.json";
Code language: C# (cs)
Read more about how to read appsettings.json.
Example – Show all files
This allows the user to select any file:
openFileDialog.Filter = "All files|*.*";
Code language: C# (cs)
Example – Show a single file group with multiple extensions
This allows the user select any file with the .config or .json extensions:
openFileDialog.Filter = "Configuration files|*.config;*.json";
Code language: C# (cs)
The two extensions are grouped together and referred to as “Configuration files.”
Example – Show two file groups with one extension each
This allows the user to select a JSON or XML file:
openFileDialog.Filter = "XML|*.xml|JSON|*.json";
Code language: C# (cs)
Read more about parsing XML files.
The reason for having these two groups (XML and JSON) is because each group appears in the dropdown:
This is useful if you want to display names that are more specific to the extensions, instead of just using a generic group name like “Configuration files.”
Select multiple files
To allow the user to select multiple files, set Multiselect=true, and get all the files they selected from the OpenFileDialog.FileNames property:
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Log files|*.log";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
foreach(var filePath in openFileDialog.FileNames)
{
//use file path
}
}
Code language: C# (cs)
This prompts the user to select a file. Since Multiselect is true, they can select multiple files at once:
When the user clicks Open, this’ll populate the OpenFileDialog.FileNames string array with all the file paths that the user selected.
Display the selected file’s metadata and contents
After the user picks a file, you can do any file operation you want. You’ll most likely want to read the file’s contents and metadata, as shown in this example:
using System.IO;
private void btnFilePicker_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Comma-separated values file|*.csv";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var filePath = openFileDialog.FileName;
txtFilePath.Text = filePath;
var fileInfo = new FileInfo(filePath);
var sb = new StringBuilder();
sb.AppendLine($"File name: {fileInfo.Name}");
sb.AppendLine($"Created At: {fileInfo.CreationTime}");
sb.AppendLine($"Modified At: {fileInfo.LastWriteTime}");
sb.AppendLine($"Bytes: {fileInfo.Length}");
txtFileInfo.Text = sb.ToString();
txtFileContent.Text = File.ReadAllText(filePath);
}
}
Code language: C# (cs)
Here’s what it looks like:
Related Articles
System.Windows.Forms.OpenFileDialog Компонент открывает диалоговое окно Windows для просмотра и выбора файлов. Чтобы открыть и прочитать выбранных файлов, можно использовать OpenFileDialog.OpenFile метод, или создать экземпляр System.IO.StreamReader класса. В следующих примерах оба подхода.
В .NET Framework, для получения или задания FileName свойство требуется уровень привилегий предоставляемый System.Security.Permissions.FileIOPermission класса. Примеры выполняют FileIOPermission разрешение проверки и может создавать исключения из-за недостатка привилегий, если выполняются в контексте частичного доверия. Дополнительные сведения см. в разделе основы управления доступом для кода.
Можно создавать и запускать эти примеры приложений .NET Framework из C# или командной строки Visual Basic. Дополнительные сведения см. в разделе сборка с помощью csc.exe из командной строки или построения из командной строки.
Начиная с .NET Core 3.0, вы можете также создавать и выполнять примеры как Windows приложений .NET Core из папки с .NET Core Windows Forms <имя_папки > .csproj файл проекта.
Пример Чтение файла в виде потока с помощью StreamReader
В следующем примере используется Windows Forms Button элемента управления Click обработчик событий, чтобы открыть OpenFileDialog с ShowDialog метод. Когда пользователь выберет файл, а также выбирает ОК, экземпляр StreamReader класс читает файл и выведет его содержимое в текстовое поле формы. Дополнительные сведения о чтении из файловых потоков, см. в разделе FileStream.BeginRead и FileStream.Read.
Warning
It looks like the sample you are looking for does not exist.
Пример Откройте файл из отфильтрованные объекты с помощью OpenFile
В следующем примере используется Button элемента управления Click обработчик событий, чтобы открыть OpenFileDialog с фильтром, который показывает только текстовые файлы. Когда пользователь выберет в текстовый файл, а также выбирает ОК, OpenFile метод используется, чтобы открыть файл в блокноте.
Warning
It looks like the sample you are looking for does not exist.
См. также
- OpenFileDialog
- OpenFileDialog — компонент
C# OpenFileDialog
C# OpenFileDialog control allows us to browse and select files on a computer in an application. A typical Open File Dialog looks like Figure 1 where you can see Windows Explorer like features to navigate through folders and select a file.
Figure 1
Creating a OpenFileDialog
We can create an OpenFileDialog control using a Forms designer at design-time or using the OpenFileDialog class in code at run-time (also known as dynamically). Unlike other Windows Forms controls, an OpenFileDialog does not have and not need visual properties like others. The only purpose of OpenFileDialog to display available colors, create custom colors and select a color from these colors. Once a color is selected, we need that color in our code so we can apply it on other controls.
Again, you can create an OpenFileDialog at design-time but it is easier to create an OpenFileDialog at run-time.
Design-time
To create an OpenFileDialog control at design-time, you simply drag and drop an OpenFileDialog control from Toolbox to a Form in Visual Studio. After you drag and drop an OpenFileDialog on a Form, the OpenFileDialog looks like Figure 2.
Figure 2
Adding an OpenFileDialog to a Form adds following two lines of code.
private System.Windows.Forms.OpenFileDialog openFileDialog1;
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
Run-time
Creating a OpenFileDialog control at run-time is merely a work of creating an instance of OpenFileDialog class, set its properties and add OpenFileDialog class to the Form controls.
First step to create a dynamic OpenFileDialog is to create an instance of OpenFileDialog class. The following code snippet creates an OpenFileDialog control object.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
ShowDialog method displays the OpenFileDialog.
openFileDialog1.ShowDialog();
Once the ShowDialog method is called, you can browse and select a file.
Setting OpenFileDialog Properties
After you place an OpenFileDialog control on a Form, the next step is to set properties.
The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 3.
Figure 3
Initial and Restore Directories
InitialDirectory property represents the directory to be displayed when the open file dialog appears first time.
openFileDialog1.InitialDirectory = @"C:\";
If RestoreDirectory property set to true that means the open file dialogg box restores the current directory before closing.
openFileDialog1.RestoreDirectory = true;
Title
Title property is used to set or get the title of the open file dialog.
openFileDialog1.Title = "Browse Text Files";
Default Extension
DefaultExtn property represents the default file name extension.
openFileDialog1.DefaultExt = "txt";
Filter and Filter Index
Filter property represents the filter on an open file dialog that is used to filter the type of files to be loaded during the browse option in an open file dialog. For example, if you need users to restrict to image files only, we can set Filter property to load image files only.
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
FilterIndex property represents the index of the filter currently selected in the file dialog box.
openFileDialog1.FilterIndex = 2;
Check File Exists and Check Path Exists
CheckFileExists property indicates whether the dialog box displays a warning if the user specifies a file name that does not exist. CheckPathExists property indicates whether the dialog box displays a warning if the user specifies a path that does not exist.
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
File Name and File Names
FileName property represents the file name selected in the open file dialog.
textBox1.Text = openFileDialog1.FileName;
If MultiSelect property is set to true that means the open file dialog box allows multiple file selection. The FileNames property represents all the files selected in the selection.
this.openFileDialog1.Multiselect = true;
foreach (String file in openFileDialog1.FileNames)
{
MessageBox.Show(file);
}
Read Only Checked and Show Read Only Files
ReadOnlyChecked property represents whether the read-only checkbox is selected and ShowReadOnly property represents whether the read-only checkbox is available or not.
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
Implementing OpenFileDialog in a C# and WinForms Applications
Now let’s create a WinForms application that will use an OpenFileDialog that has two Button controls, a TextBox, and a container control. The Form looks like Figure 4.
Figure 4
The Browse button click event handler will show an open file dialog and users will be able to select text files. The open file dialog looks like Figure 5.
Figure 5
The following code snippet is the code for Browse button click event handler. Once a text file is selected, the name of the text file is displayed in the TextBox.
private void BrowseButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = @"D:\",
Title = "Browse Text Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "txt",
Filter = "txt files (*.txt)|*.txt",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
The code for Browse Multiple Files button click event handler looks like following.
private void BrowseMultipleButton_Click(object sender, EventArgs e)
{
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" +
"All files (*.*)|*.*";
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "Select Photos";
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
try
{
PictureBox imageControl = new PictureBox();
imageControl.Height = 400;
imageControl.Width = 400;
Image.GetThumbnailImageAbort myCallback =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap = new Bitmap(file);
Image myThumbnail = myBitmap.GetThumbnailImage(300, 300,
myCallback, IntPtr.Zero);
imageControl.Image = myThumbnail;
PhotoGallary.Controls.Add(imageControl);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
public bool ThumbnailCallback()
{
return false;
}
The output looks like Figure 6.
Summary
An OpenFileDialog control allows users to launch Windows Open File Dialog and let them select files. In this article, we discussed how to use a Windows Open File Dialog and set its properties in a Windows Forms application.
