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

c#, dialog, file-io, string

Solution

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();

Problem

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?

Original source