Openfiledialog c windows forms диалоговое окно

Открытие и сохранение файлов с помощью OpenFileDialog и SaveFileDialog в Windows Forms и Visual C#

Последнее обновление: 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. После добавления они отобразятся внизу дизайнера формы. В итоге форма будет выглядеть примерно так:

OpenFileDialog и SaveFileDialog в Windows Forms

Теперь изменим код формы:

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("Файл открыт");
    }
}

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

136

Часть I. Microsoft Visual C++ 2010

Таблица 3.29 (окончание)

Свойство

Значение

toolStripMenuItem1.Image

toolStripMenuItem2.Text

Открыть

toolStripMenuItem2.Image

toolStripMenuItem3.Text

Сохранить

toolStripMenuItem3.Image

toolStripMenuItem4.Text

Печать

toolStripMenuItem4.Image

toolStripMenuItem5.Text

Выход

toolStripMenuItem5.ShortutKeys

Alt+F4

paramToolStripMenuItem.Text

Параметры

toolStripMenuItem6.Text

Панель инструментов

toolStripMenuItem6.Checked

True

toolStripMenuItem7.Text

Шрифт

helpToolStripMenuItem.Text

Справка

toolStripMenuItem8.Text

Справочная информация

toolStripMenuItem8.Text

О программе

Компонент OpenFileDialog (рис. 3.47) представляет собой диалоговое окно (диалог) Открыть. Свойства компонента приведены в табл. 3.30.

Таблица 3.30. Свойства компонента OpenFileDialog

Свойство

Описание

Title

Текст в заголовке окна. Если значение свойства не задано,

то в заголовке отображается текст Открыть

InitialDirectory

Каталог, содержимое которого отображается при появлении диа-

лога на экране

Filter

Свойство задает один или несколько фильтров файлов.

В окне отображаются только те файлы, имена которых соответст-

вуют выбранному фильтру. Фильтр задается строкой вида Описа-

ние|Маска. Например, фильтр Текст|*.txt задает, что в окне диа-

лога следует отображать только текстовые файлы. Фильтр может

состоять из нескольких элементов, например: Текст|*.txt|Все

файлы|*.*

Глава 3. Базовые компоненты

137

Таблица 3.30 (окончание)

Свойство

Описание

FilterIndex

Если фильтр состоит из нескольких элементов, например,

Текст|*.txt|Все файлы|*.*, то значение свойства задает фильтр,

который будет использоваться в момент появления диалога на

экране

FileName

Имя выбранного пользователем файла

RestoreDirectory

Признак необходимости отображать содержимое каталога, ука-

занного в свойстве InitialDirectory, при каждом появлении

окна. Если значение свойства равно False, то при следующем

появлении окна отображается содержимое каталога, выбранного

пользователем в предыдущий раз

Рис. 3.47. Компонент OpenFileDialog

Отображение диалога Открыть обеспечивает метод ShowDialog. Его значением является код клавиши, нажатием которой пользователь завершил диалог (закрыл окно).

В качестве примера в листинге 3.16 приведен фрагмент программы MEdit — функция обработки события Click на команде Открыть меню Файл.

138

Часть I. Microsoft Visual C++ 2010

Листинг 3.16. Загрузка текста в компонент TextBox

// выбор в меню Файл команды Открыть

private: System::Void toolStripMenuItem2_Click(System::Object^ sender, System::EventArgs^ e)

{

System::Windows::Forms::DialogResult dr; int r;

r = SaveText(); // сохранить текст, находящийся в поле компонента

if (r == 0)

{

openFileDialog1->FileName = String::Empty;

// отобразить диалог Открыть

dr = openFileDialog1->ShowDialog();

if (dr == System::Windows::Forms::DialogResult::OK)

{

fn = openFileDialog1->FileName;

// отобразить имя файла в заголовке окна this->Text = fn;

try

{

// считываем данные из файла

System::IO::StreamReader^ sr =

gcnew System::IO::StreamReader(fn);

textBox1->Text = sr->ReadToEnd(); textBox1->SelectionStart = textBox1->TextLength;

sr->Close(); textChanged = false;

}

catch ( System::IO::FileLoadException^ e)

{

MessageBox::Show(«Ошибка:n» + e->Message, «MEdit», MessageBoxButtons::OK, MessageBoxIcon::Error);

}

}

}

}

Глава 3. Базовые компоненты

139

SaveFileDialog

Компонент SaveFileDialog (рис. 3.48) представляет собой стандартное диалоговое окно Сохранить. Свойства компонента приведены в табл. 3.31.

Рис. 3.48. Компонент SaveFileDialog

Таблица 3.31. Свойства компонента SaveFileDialog

Свойство

Описание

Title

Текст в заголовке окна. Если значение свойства не задано,

то в заголовке отображается текст Сохранить как

FileNane

Полное имя файла, которое задал пользователь. В общем слу-

чае оно образуется из имени каталога, содержимое которого

отображается в диалоговом окне, имени файла, которое пользо-

ватель ввел в поле Имя файла, и расширения, заданного зна-

чением свойства DefaultExt

DefaultExt

Расширение файла по умолчанию. Если пользователь в поле

Имя файла не укажет расширение, то к имени файла будет до-

бавлено расширение (при условии, что значение свойства

AddExtension равно True), заданное значением этого свойства

InitialDirectory

Каталог, содержимое которого отображается при появлении

диалога на экране

140

Часть I. Microsoft Visual C++ 2010

Таблица 3.31 (окончание)

Свойство

Описание

RestoreDirectory

Признак необходимости отображать содержимое каталога, ука-

занного в свойстве InitialDirectory, при каждом появлении

окна. Если значение свойства равно False, то при следующем

появлении окна отображается содержимое каталога, выбранно-

го пользователем в предыдущий раз

CheckPathExists

Признак необходимости проверки существования каталога,

в котором следует сохранить файл. Если указанного каталога

нет, то выводится информационное сообщение

CheckFileExists

Признак необходимости проверки существования файла

с заданным именем. Если значение свойства равно True и файл

с указанным именем уже существует, появляется окно запроса,

в котором пользователь может подтвердить необходимость за-

мены (перезаписи) существующего файла

Filter

Свойство задает один или несколько фильтров файлов.

В окне отображаются только те файлы, имена которых соответ-

ствуют выбранному фильтру. Фильтр задается строкой вида

Описание|Маска. Например, фильтр Текст|*.txt задает, что

в окне диалога следует отображать только текстовые файлы.

Фильтр может состоять из нескольких элементов, например:

Текст|*.txt|Все файлы|*.*

FilterIndex

Если фильтр состоит из нескольких элементов, например,

Текст|*.txt|Все файлы|*.*, то значение свойства задает фильтр,

который будет использоваться в момент появления диалога на

экране

Отображение диалога Сохранить обеспечивает метод ShowDialog. Его значением является код клавиши, нажатием которой пользователь завершил диалог (закрыл окно).

В качестве примера в листинге 3.17 приведен фрагмент программы MEdit — функция SaveText, которая записывает в файл текст, находящийся в поле редактирования.

Листинг 3.17. Сохранение текста в файле

//Проверяет, есть ли изменения в тексте, и, если изменения есть,

//сохраняет текст в файле.

//Функция возвращает -1, если пользователь отказался от выполнения

//операции (нажал в окне Сохранить кнопку Отмена).

private: int SaveText()

{

System::Windows::Forms::DialogResult dr;

Глава 3. Базовые компоненты

141

int r;

r = 0;

if (textChanged)

{

dr = MessageBox::Show(

«В текст внесены изменения. Сохранить измененный текст?»,

«MEdit»,

MessageBoxButtons::YesNoCancel,

MessageBoxIcon::Warning); switch (dr)

{

case System::Windows::Forms::DialogResult::Yes: r = TextToFile();

break;

case System::Windows::Forms::DialogResult::No: r = 0;

break;

case System::Windows::Forms::DialogResult::Cancel: r = -1;

break;

};

}

return r;

}

Полный текст программы MEdit, демонстрирующий использование компо-

нентов MenuStrip, ToolStrip, ToolTip, OpenFileDialog, SaveFaleDialog,

PrintDialog и FontDialog, приведен в листинге 3.18. Обратите внимание, в модуль формы надо вставить ссылку на пространство имен System::IO.

Листинг 3.18. MEdit

// конструктор

Form1(void)

{

InitializeComponent();

textBox1->ScrollBars = ScrollBars::Vertical; textBox1->Text = «»;

this->Text = «MEdit — Новый документ»;

142

Часть I. Microsoft Visual C++ 2010

//отобразить панель инструментов toolStrip1->Visible = true; toolStripMenuItem6->Checked = true;

//назначаем файл справки

//helpProvider1.HelpNamespace = «nkedit.chm»;

//настройка компонента openDialog1 openFileDialog1->DefaultExt = «txt»; openFileDialog1->Filter = «Текст|*.txt»; openFileDialog1->Title = «Открыть документ»; openFileDialog1->Multiselect = false;

//настройка компонента saveDialog1 saveFileDialog1->DefaultExt = «txt»; saveFileDialog1->Filter = «Текст|*.txt»; saveFileDialog1->Title = «Сохранить документ»;

fn = String::Empty; textChanged = false;

}

private:

String^ fn; // имя файла

bool textChanged; // true — в текст внесены изменения

// изменился текст в поле компонента textBox1

private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e)

{

textChanged = true; // текст изменен

}

//Записывает текст в файл.

//Возвращает 0 или -1, если пользователь

//в окне Сохранить нажмет кнопку Отмена private: int TextToFile()

{

System::Windows::Forms::DialogResult dr; int r = 0;

if (fn == String::Empty)

{

//Это новый документ.

//Запросить у пользователя имя файла.

Глава 3. Базовые компоненты

143

// Отобразить диалог Сохранить

dr = saveFileDialog1->ShowDialog();

if (dr == System::Windows::Forms::DialogResult::OK)

{

fn = saveFileDialog1->FileName; r = 0;

}

else

//В окне Сохранить пользователь

//сделал щелчок на кнопке Отмена r = -1;

}

// сохранить файл if (r == 0)

{

try

{

// получим информацию о файле fn

System::IO::FileInfo^ fi = gcnew System::IO::FileInfo(fn);

// поток для записи

System::IO::StreamWriter^ sw = fi->CreateText(); sw->Write(textBox1->Text);

sw->Close(); // закрываем поток textChanged = false;

r = 0;

}

catch (System::IO::IOException^ e)

{

MessageBox::Show(e->ToString(), «MEdit», MessageBoxButtons::OK,

MessageBoxIcon::Error);

}

}

return r;

}

//Проверяет, есть ли изменения в тексте, и сохраняет текст в файле.

//Возвращает 0 или -1, если пользователь

//отказался от выполнения операции (нажал кнопку Отмена)

144

Часть I. Microsoft Visual C++ 2010

private: int SaveText()

{

System::Windows::Forms::DialogResult dr;

int r;

r = 0;

if (textChanged)

{

dr = MessageBox::Show(

«В текст внесены изменения. Сохранить измененный текст?»,

«MEdit»,

MessageBoxButtons::YesNoCancel,

MessageBoxIcon::Warning); switch (dr)

{

case System::Windows::Forms::DialogResult::Yes: r = TextToFile();

break;

case System::Windows::Forms::DialogResult::No: r = 0;

break;

case System::Windows::Forms::DialogResult::Cancel: r = -1;

break;

};

}

return r;

}

// Открыть документ private: void OpenDocument()

{

System::Windows::Forms::DialogResult dr; int r;

r = SaveText();

if (r == 0)

{

openFileDialog1->FileName = String::Empty;

Глава 3. Базовые компоненты

145

// отобразить диалог Открыть

dr = openFileDialog1->ShowDialog();

if (dr == System::Windows::Forms::DialogResult::OK)

{

fn = openFileDialog1->FileName;

// отобразить имя файла в заголовке окна this->Text = fn;

try

{

// считываем данные из файла

System::IO::StreamReader^ sr =

gcnew System::IO::StreamReader(fn);

textBox1->Text = sr->ReadToEnd(); textBox1->SelectionStart = textBox1->TextLength;

sr->Close(); textChanged = false;

}

catch ( System::IO::FileLoadException^ e)

{

MessageBox::Show(«Ошибка:n» + e->Message, «MEdit», MessageBoxButtons::OK, MessageBoxIcon::Error);

}

}

}

}

// Сохранить документ private: void SaveDocument()

{

int r;

r = SaveText();

if (r == 0)

{

this->Text = fn;

146

Часть I. Microsoft Visual C++ 2010

textChanged = false;

}

}

// Создать документ private: void NewDocument()

{

int r;

r = SaveText();

if (r == 0)

{

this->Text = «Новый документ»; textBox1->Clear(); textChanged = false;

fn = String::Empty;

}

}

// выбор в меню Файл команды Открыть

private: System::Void toolStripMenuItem2_Click(System::Object^ sender, System::EventArgs^ e)

{

OpenDocument();

}

// выбор в меню Файл команды Сохранить

private: System::Void toolStripMenuItem3_Click(System::Object^ sender, System::EventArgs^ e)

{

SaveDocument();

}

// выбор в меню Файл команды Создать

private: System::Void toolStripMenuItem1_Click(System::Object^ sender, System::EventArgs^ e)

{

NewDocument();

}

// выбор в меню Файл команды Печать

private: System::Void toolStripMenuItem4_Click(System::Object^ sender, System::EventArgs^ e)

Глава 3. Базовые компоненты

147

{

printDialog1->ShowDialog();

}

// выбор в меню Файл команды Выход

private: System::Void toolStripMenuItem5_Click(System::Object^ sender, System::EventArgs^ e)

{

this->Close();

}

// выбор в меню Параметры команды Панель инструментов

private: System::Void toolStripMenuItem6_Click(System::Object^ sender, System::EventArgs^ e)

{

// отобразить/скрыть панель инструментов toolStrip1->Visible = ! toolStrip1->Visible; toolStripMenuItem6->Checked = ! toolStripMenuItem6->Checked;

}

// выбор в меню Параметры команды Шрифт

private: System::Void toolStripMenuItem7_Click(System::Object^ sender, System::EventArgs^ e)

{

fontDialog1->Font = textBox1->Font; if (fontDialog1->ShowDialog() ==

System::Windows::Forms::DialogResult::OK)

{

textBox1->Font = fontDialog1->Font;

}

}

// щелчок на кнопке Создать

private: System::Void toolStripButton1_Click(System::Object^ sender, System::EventArgs^ e)

{

NewDocument();

}

// щелчок на кнопке Открыть

private: System::Void toolStripButton2_Click(System::Object^ sender, System::EventArgs^ e)

148

Часть I. Microsoft Visual C++ 2010

{

OpenDocument();

}

// щелчок на кнопке Сохранить

private: System::Void toolStripButton3_Click(System::Object^ sender, System::EventArgs^ e)

{

SaveDocument();

}

// щелчок на кнопке Печать

private: System::Void toolStripButton4_Click(System::Object^ sender, System::EventArgs^ e)

{

printDialog1->ShowDialog();

}

// попытка закрыть окно программы

private: System::Void Form1_FormClosing(System::Object^ sender, System::Windows::Forms::FormClosingEventArgs^ e)

{

int r;

r = SaveText();

if (r != 0)

{

e->Cancel = true;

}

}

// выбор в меню Справка команды О программе

private: System::Void toolStripMenuItem9_Click(System::Object^ sender, System::EventArgs^ e)

{

//Чтобы класс Form2 стал доступен, в начало программы надо вставить

//директиву #include «Form2.h»,

//где Form2.h — модуль, в котором определен класс Form2

Form2^ about = gcnew Form2();

about->ShowDialog();

}

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.

OpenFileDialog In C#

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.

OpenFileDialog In C#

Figure 2 

Adding an OpenFileDialog to a Form adds following two lines of code.

  1. private System.Windows.Forms.OpenFileDialog openFileDialog1;  
  2. 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.

  1. OpenFileDialog openFileDialog1 = new OpenFileDialog();  

ShowDialog method displays the OpenFileDialog.

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

OpenFileDialog In C#

Figure 3 

Initial and Restore Directories

InitialDirectory property represents the directory to be displayed when the open file dialog appears first time.

  1. openFileDialog1.InitialDirectory = @«C:»;  

If RestoreDirectory property set to true that means the open file dialogg box restores the current directory before closing.

  1. openFileDialog1.RestoreDirectory = true;  

Title

Title property is used to set or get the title of the open file dialog.

  1. openFileDialog1.Title = «Browse Text Files»;  

Default Extension

DefaultExtn property represents the default file name extension.

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

  1. openFileDialog1.Filter = «txt files (*.txt)|*.txt|All files (*.*)|*.*»;  

FilterIndex property represents the index of the filter currently selected in the file dialog box.

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

  1. openFileDialog1.CheckFileExists = true;  
  2. openFileDialog1.CheckPathExists = true;  

File Name and File Names

FileName property represents the file name selected in the open file dialog.

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

  1. this.openFileDialog1.Multiselect = true;  
  2. foreach (String file in openFileDialog1.FileNames)   
  3. {   
  4.   MessageBox.Show(file);  
  5. }  

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.

  1. openFileDialog1.ReadOnlyChecked = true;  
  2. 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.

  1. private void BrowseButton_Click(object sender, EventArgs e)  
  2. {  
  3.     OpenFileDialog openFileDialog1 = new OpenFileDialog  
  4.     {  
  5.         InitialDirectory = @«D:»,  
  6.         Title = «Browse Text Files»,  
  7.   
  8.         CheckFileExists = true,  
  9.         CheckPathExists = true,  
  10.   
  11.         DefaultExt = «txt»,  
  12.         Filter = «txt files (*.txt)|*.txt»,  
  13.         FilterIndex = 2,  
  14.         RestoreDirectory = true,  
  15.   
  16.         ReadOnlyChecked = true,  
  17.         ShowReadOnly = true  
  18.     };  
  19.   
  20.     if (openFileDialog1.ShowDialog() == DialogResult.OK)  
  21.     {  
  22.         textBox1.Text = openFileDialog1.FileName;  
  23.     }  
  24. }  

The code for Browse Multiple Files button click event handler looks like following.

  1. private void BrowseMultipleButton_Click(object sender, EventArgs e)  
  2. {  
  3.     this.openFileDialog1.Filter =  
  4. «Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|» +  
  5. «All files (*.*)|*.*»;  
  6.   
  7.     this.openFileDialog1.Multiselect = true;  
  8.     this.openFileDialog1.Title = «Select Photos»;  
  9.   
  10.     DialogResult dr = this.openFileDialog1.ShowDialog();  
  11.     if (dr == System.Windows.Forms.DialogResult.OK)  
  12.     {  
  13.         foreach (String file in openFileDialog1.FileNames)  
  14.         {  
  15.             try  
  16.             {  
  17.                 PictureBox imageControl = new PictureBox();  
  18.                 imageControl.Height = 400;  
  19.                 imageControl.Width = 400;  
  20.   
  21.                 Image.GetThumbnailImageAbort myCallback =  
  22.                         new Image.GetThumbnailImageAbort(ThumbnailCallback);  
  23.                 Bitmap myBitmap = new Bitmap(file);  
  24.                 Image myThumbnail = myBitmap.GetThumbnailImage(300, 300,  
  25.                     myCallback, IntPtr.Zero);  
  26.                 imageControl.Image = myThumbnail;  
  27.   
  28.                 PhotoGallary.Controls.Add(imageControl);  
  29.             }  
  30.             catch (Exception ex)  
  31.             {  
  32.                 MessageBox.Show(«Error: « + ex.Message);  
  33.             }  
  34.         }  
  35.     }  
  36. }  
  37. public bool ThumbnailCallback()  
  38. {  
  39.     return false;  
  40. }  

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. 

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

I am new to the OpenFileDialog function, but have the basics figured out. What I need to do is open a text file, read the data from the file (text only) and correctly place the data into separate text boxes in my application. Here’s what I have in my «open file» event handler:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        MessageBox.Show(theDialog.FileName.ToString());
    }
}

The text file I need to read is this (for homework, I need to read this exact file), It has an employee number, name, address, wage, and hours worked:

1
John Merryweather
123 West Main Street
5.00 30

In the text file I was given, there are 4 more employees with info immediately after this in the same format. You can see that the employee wage and hours are on the same line, not a typo.

I have an employee class here:

public class Employee
{
    //get and set properties for each 
    public int EmployeeNum { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public double Wage { get; set; }
    public double Hours { get; set; }

    public void employeeConst() //constructor method
    {
        EmployeeNum = 0;
        Name = "";
        Address = "";
        Wage = 0.0;
        Hours = 0.0;
    }

    //Method prologue
    //calculates employee earnings
    //parameters: 2 doubles, hours and wages
    //returns: a double, the calculated salary
    public static double calcSalary(double h, double w)
    {
        int OT = 40;
        double timeandahalf = 1.5;
        double FED = .20;
        double STATE = .075;
        double OThours = 0;
        double OTwage = 0;
        double OTpay = 0;
        double gross = 0; ;
        double net = 0;
        double net1 = 0;
        double net2 = 0;
        if (h > OT)
        {
            OThours = h - OT;
            OTwage = w * timeandahalf;
            OTpay = OThours * OTwage;
            gross = w * h;
            net = gross + OTpay;
        }
        else
        {
            net = w * h;
        }

        net1 = net * FED; //the net after federal taxes
        net2 = net * STATE; // the net after state taxes

        net = net - (net1 + net2);
        return net; //total net
    }
}

So I need to pull the text from that file into my Employee class, then output the data to the correct textbox in the windows forms application. I am having trouble understanding how to do this right. Do I need to use a streamreader? Or is there another, better way in this instance? Thank you.

В данной заметке я решил кратко, а главное наглядно продемонстрировать пример создания окна для выбора файла.

Сразу оговорюсь, что если Вас интересует окно для выбора директории, то Вам нужно смотреть данную заметку.
По сравнению с окном для выбора папок, форма для выбора файлов более богата настройками. Однако в целом принцип работы класса OpenFileDialog не отличается от класса FolderBrowserDialog. Создадим новую форму и перейдем к ее коду. Там уже будет создан конструктор нашей формы, именно там мы и будем вызывать наше окно, для выбора файла.

public Form1()
        {
            InitializeComponent();
            OpenFileDialog OPF = new OpenFileDialog();
            if (OPF.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show(OPF.FileName);
            }
        }

Пример уже вполне рабочий, однако использовать данный класс так не стоит. Главная причина этому — форма показывает нам абсолютно все файлы. В жизни такое бывает редко, поэтому давайте ограничим отображение только файлами txt и cs. Для этого нам понадобиться свойство Filter.

OPF.Filter = "Файлы txt|*.txt|Файлы cs|*.cs";

Фильтр задается через разделитель по следующему принципу: «ОписаниеТипаФайла|МаскаПоискаФайла[|…]». Таким образом в нашем примере в качестве описания выступают фразы «Файлы txt» и «Файлы cs», а в качества масок «*.txt» и «*.cs» — что соответствует любым файлам с расширением txt и cs. Так же мы можем явно задать имя файла, который нам нужно выбрать.

OPF.Filter = "Файлы txt|*.txt|Файлы cs|Form1.cs";

Так же мы можем разрешить пользователю выбор нескольких файлов сразу, для этого необходимо поставить свойство Multiselect = true. Однако тогда, для полечения всех имен выбранных файлов необходимо будет использовать массив FileNames вместо свойства FileName.

public Form1()
        {
            InitializeComponent();
            OpenFileDialog OPF = new OpenFileDialog();
            OPF.Multiselect = true; 
            if (OPF.ShowDialog() == DialogResult.OK)
            {
                foreach (string file in OPF.FileNames)
                {
                    MessageBox.Show(file);
                }
            }
        }

В целом если покопаться в свойствах класса OpenFileDialog можно найти еще несколько забавных свойств, однако основные из них, я описал выше.

In this article I will explain with an example, how to use the Windows Forms (WinForms) OpenFileDialog Box control in C# and VB.Net.

In Windows Forms (WinForms) applications, the OpenFileDialog Box is used to select single or multiple files from the Windows Folders or Directories.

Form Controls

The following Windows Form consists of two Buttons.

Windows Forms (WinForms) OpenFileDialog Box Tutorial with example in C# and VB.Net

Then you need to drag and add an OpenFileDialog control to the form from the Dialogs section of the Visual Studio ToolBox.

Windows Forms (WinForms) OpenFileDialog Box Tutorial with example in C# and VB.Net

Once added it will be displayed in the section below the Form design as shown below.

Windows Forms (WinForms) OpenFileDialog Box Tutorial with example in C# and VB.Net

Namespaces

You will need to import the following namespace.

C#

VB.Net

Selecting Single File with the OpenFileDialog Box

In order to select a Single File, the Multiselect property of the OpenFileDialog Box needs to be set to False which is its default value.

The Path of the selected File is available in the FileName property of the OpenFileDialog Box.

The Name and Path of the selected File is displayed in the Windows Forms MessageBox.

C#

private void btnSelect_Click(object sender, EventArgs e)

{

    openFileDialog1.Multiselect = false;

    if (openFileDialog1.ShowDialog() == DialogResult.OK)

    {

        string fileName = Path.GetFileName(openFileDialog1.FileName);

        string filePath = openFileDialog1.FileName;

        MessageBox.Show(fileName + » — « + filePath);

    }

}

VB.Net

Private Sub btnSelect_Click(sender As System.Object, e As System.EventArgs) Handles btnSelect.Click

    openFileDialog1.Multiselect = False

    If openFileDialog1.ShowDialog() = DialogResult.OK Then

        Dim fileName As String = Path.GetFileName(openFileDialog1.FileName)

        Dim filePath As String = openFileDialog1.FileName

        MessageBox.Show(fileName & » — « & filePath)

    End If

End Sub

Windows Forms (WinForms) OpenFileDialog Box Tutorial with example in C# and VB.Net

Selecting Multiple Files with the OpenFileDialog Box

In order to select a Multiple Files, the Multiselect property of the OpenFileDialog Box needs to be set to True.

The Path of the selected File is available in the FileName property of the OpenFileDialog Box.

The Name and Path of the selected Files are displayed in the Windows Forms MessageBox.

C#

private void btnSelectMultiple_Click(object sender, EventArgs e)

{

    string message = «»;

    openFileDialog1.Multiselect = true;

    if (openFileDialog1.ShowDialog() == DialogResult.OK)

    {

        foreach (string file in openFileDialog1.FileNames)

        {

            message += Path.GetFileName(file) + » — « + file + Environment.NewLine;

        }

        MessageBox.Show(message);

    }

}

VB.Net

Private Sub btnSelectMultiple_Click(sender As System.Object, e As System.EventArgs) Handles btnSelectMultiple.Click

    Dim message As String = «»

    openFileDialog1.Multiselect = True

    If openFileDialog1.ShowDialog() = DialogResult.OK Then

        For Each file As String In openFileDialog1.FileNames

            message += Path.GetFileName(file) & » — « & file & Environment.NewLine

        Next

        MessageBox.Show(message)

    End If

End Sub

Windows Forms (WinForms) OpenFileDialog Box Tutorial with example in C# and VB.Net

Downloads

OpenFileDialogBox.zip

Понравилась статья? Поделить с друзьями:
  • Openconnect gui vpn client windows 10 как настроить
  • Opencll dll скачать для windows 10
  • Opencl скачать для windows 10 x64 официальный сайт
  • Opencl последняя версия для windows 10 x64
  • Opencl драйвер скачать для windows 10 x64