In C # WinForms, I want to specify the standard directory selection from where files will be read. I would like something to be like an indication of the installation path of the program.

What is needed: there is a button calling the explorer, and when you specify the desired path in it, it is automatically pulled into the TextBox string.

  • And what's the problem? Hangs TextBox, and next to the button. On the button you hang up an event handler that opens FileDialog, a file is selected there, and then you slip it into your TextBox. - iluxa1810
  • one

2 answers 2

This is done quite simply. For example, we drop the Button component on the form — a button, on click on which we will open the folder selection dialog and the FolderBrowserDialog folder selection component FolderBrowserDialog :

enter image description here

After this, click twice on the button, a method of processing the click on this button will be automatically created and we will add a simple processing code:

 private string folderName; // тут будем хранить путь к папке private void button1_Click(object sender, EventArgs e) { // показать диалог выбора папки DialogResult result = folderBrowserDialog1.ShowDialog(); // если папка выбрана и нажата клавиша `OK` - значит можно получить путь к папке if (result == DialogResult.OK) { // запишем в нашу переменную путь к папке folderName = folderBrowserDialog1.SelectedPath; } } 

Actually the link to the documentation itself: FolderBrowserDialog there is an example of code. To write the resulting value to the desired TextBox , simply add a TextBox element to the form and instead of a line of code:

 folderName = folderBrowserDialog1.SelectedPath; 

Perform the assignment of text to the previously added TextBox through its Text property like this:

 textBox1.Text = folderBrowserDialog1.SelectedPath; 

A couple more links:

    Here is the code to select a folder:

     using(var fbd = new FolderBrowserDialog()) { if (fbd.ShowDialog() == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { // вот выбранный путь, его можно потом засунуть в ваш textbox string path = fbd.SelectedPath; } }