Browse to a Directory and have the Path stored in a string (C#)

10,267

Solution 1

The type you are looking for is the OpenFileDialog

http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx

The basic usage is the following

using (FileDialog fileDialog = new OpenFileDialog()) {
  if (DialogResult.Ok == fileDialog.ShowDialog()) {
    string fileName = fileDialog.FileName;
    ...
  }
}

EDIT

Comments clarified OP is looking to open a directory vs. a file. For this you need the FolderBrowseDialog

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Solution 2

For choosing directory you should use FolderBrowserDialog. It's a control from WinForms. WPF doesn't have it's own.

For example:

var dialog = new FolderBrowserDialog();
var result = dialog.ShowDialog();
if (result == DialogResult.OK)
    // ...

Don't forget to add reference to the System.Windows.Forms.

Solution 3

Simply do this on Button Click

        FileDialog fileDialog = new OpenFileDialog();
        fileDialog.ShowDialog();
        folderpathTB.Text = fileDialog.FileName;

(folderpathTB is name of TextBox where I wana put the file path, OR u can assign it to a string variable too)

Share:
10,267
Steve Way
Author by

Steve Way

Updated on June 04, 2022

Comments

  • Steve Way
    Steve Way almost 2 years

    I'm trying to make this program in C# using WPF in Visual Studio. This is basically what it has to do.

    When a button called "Browse" is clicked on the main form, it will open up a new form/window that let's the user browse to any directory that he chooses. After he selects the folder and clicks "Open" (or some other button on that form), the path of that directory, for example, "C:\temp" will be stored in a string variable so it can used later.

    My first problem is, what do I write in the even handler of the "Browse" button that will open up a window that let's the user browse and select a folder? Is there a default window I can use or do I have to create a new form for it? Please note, the user has to select a folder, not a file like the default "Open" window.

    Secondly, how do I reference a string variable so that it stores the path of the directory that the user selected?