Как открыть файл через windows forms

Последнее обновление: 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("Файл открыт");
    }
}

По нажатию на первую кнопку будет открываться окно открытия файла. После выбора файла он будет считываться, а его текст будет отображаться в
текстовом поле. Клик на вторую кнопку отобразит окно для сохранения файла, в котором надо установить его название. И после этого произойдет сохранение
текста из текстового поля в файл.

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.

C# OpenFileDialog

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.

OpenFileDialog In C#

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.

OpenFileDialog In C#

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.

OpenFileDialog control in C#

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. 

Распознавание голоса и речи на C#

UnmanagedCoder 05.05.2025

Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .

Реализация своих итераторов в C++

NullReferenced 05.05.2025

Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .

Разработка собственного фреймворка для тестирования в C#

UnmanagedCoder 04.05.2025

C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .

Распределенная трассировка в Java с помощью OpenTelemetry

Javaican 04.05.2025

Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .

Шаблоны обнаружения сервисов в Kubernetes

Mr. Docker 04.05.2025

Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .

Создаем SPA на C# и Blazor

stackOverflow 04.05.2025

Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .

Реализация шаблонов проектирования GoF на C++

NullReferenced 04.05.2025

«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .

C# и сети: Сокеты, gRPC и SignalR

UnmanagedCoder 04.05.2025

Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .

Создание микросервисов с Domain-Driven Design

ArchitectMsa 04.05.2025

Архитектура микросервисов за последние годы превратилась в мощный архитектурный подход, который позволяет разрабатывать гибкие, масштабируемые и устойчивые системы. А если добавить сюда ещё и. . .

Многопоточность в C++: Современные техники C++26

bytestream 04.05.2025

C++ долго жил по принципу «один поток — одна задача» — как старательный солдатик, выполняющий команды одну за другой. В то время, когда процессоры уже обзавелись несколькими ядрами, этот подход стал. . .

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:

Open file dialog, showing a list of files for the user to select

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).

Shows the OpenFileDialog control in the Toolbox, and shows this control dragged to the form with its property list opened. The InitialDirectory property is set to C:\logs\

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:

Open file dialog showing how the filter property controls what shows in the dropdown and what files 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:

Open file dialog dropdown showing multiple file groups specified in the filter string

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:

Open file dialog showing the user selecting multiple files

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:

Displaying the selected file's metadata (Name, created at, modified at, and size in bytes) and the file's content (in this case, it's rows of NFL team stats)

Related Articles

This C# tutorial demonstrates the OpenFileDialog control in Windows Forms.

OpenFileDialog allows users to browse folders and select files.

It is available in Windows Forms and 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.

Intro. 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.

Note: This entry describes a control that «displays a dialog box that prompts the user to open a file.»

With OpenFileDialog, you can only change properties in the Properties pane. 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.

You can add a Button control—this can be clicked on to call into the OpenFileDialog window. To add a Button, find the Button icon in the Toolbox and drag it to an area in your Windows Forms window.

Tip: 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.
	}
    }
}

The example demonstrates the use of 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.
	}
    }
}

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.

Note: The above program for simplicity does not have a TextBox control to display the file it opens.

Tip: If you want to show the file contents in another control, add a TextBox and assign it to the text string.

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. Recommended. See blogs.msdn.com link.

AutoUpgradeEnabled for Open File Dialog

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.

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.

And: We saw how to add an OpenFileDialog, set its properties, and use it in C# code.


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

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как посмотреть ntp сервер в windows server
  • Как включить вложенную виртуализацию nested vt x virtualbox в системах в microsoft windows
  • Texas instruments pcixx12 integrated flashmedia controller for windows 10
  • Конвертация heic в jpg windows
  • Bitdefender windows 8 security