User input: Folder picker

folder browser example

Pick a folder, any folder...


While not directly related to the NXOpen API, the folder picker dialog will find many uses in your journals. Sure, you could use an input box and force the user to type the entire directory path, but that is just sooooo 1982. Users have come to expect something less cumbersome and error prone - that something is the folder picker dialog!

Using a folder picker dialog is not much more difficult that using a message box, which is to say it is pretty easy. Copy and paste the code below into a new journal file to see what it can do for you.


'December 14, 2012
'example code demonstrating the use of the folder browser dialog
'tested on NX8, but will probably run on NX3 or higher
Option Strict Off
Imports System
Imports System.Windows.Forms
Imports NXOpen
Module Module1
    '  Explicit Activation
    '      This entry point is used to activate the application explicitly
    Sub Main()
        Dim theSession As Session = Session.GetSession()
		Dim workPart As Part = theSession.Parts.Work
        Dim lw As ListingWindow = theSession.ListingWindow
        Dim outputFolder As String = ""
        Dim FolderBrowserDialog1 As New FolderBrowserDialog
        ' Then use the following code to create the Dialog window
        ' Change the .SelectedPath property to the default location
        With FolderBrowserDialog1
            ' Desktop is the root folder in the dialog.
            .RootFolder = Environment.SpecialFolder.Desktop
            '.RootFolder = Environment.SpecialFolder.MyDocuments
            '.RootFolder = Environment.SpecialFolder.MyPictures
            '.RootFolder = Environment.SpecialFolder.UserProfile
            ' Select the C:\ directory on entry.
            .SelectedPath = "C:\"
            '.SelectedPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            '.SelectedPath = My.Computer.FileSystem.SpecialDirectories.Temp
            ' Prompt the user with a custom message.
            .Description = " folder picker example"
            If .ShowDialog = DialogResult.OK Then
                outputFolder = .SelectedPath
                'user pressed cancel, exit journal
                Exit Sub
            End If
        End With
        Dim testFile As String = "12345.dat"
        lw.WriteLine("Folder selected: " & outputFolder)
        'combine the selected folder and file name into a complete path specification
        lw.WriteLine("Full path for testFile: " & IO.Path.Combine(outputFolder, testFile))
    End Sub
    Public Function GetUnloadOption(ByVal dummy As String) As Integer
        'Unloads the image when the NX session terminates
        GetUnloadOption = NXOpen.Session.LibraryUnloadOption.AtTermination
        '----Other unload options-------
        'Unloads the image immediately after execution within NX
        'GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Immediately
        'Unloads the image explicitly, via an unload dialog
        'GetUnloadOption = NXOpen.Session.LibraryUnloadOption.Explicitly
    End Function
End Module


To use the folder picker, the first thing you will need is a reference to System.Windows.Forms; we've seen this before when using the message box or input box provided by Windows. This reference basically just let's Windows know that you will be calling on it to do some work for you - hey that's what it is there for! Next, we'll need a string variable to hold the output (directory path) from the folder dialog. The folder browser dialog object is created, this object has several properties and methods that we can modify to customize our folder picker. To save on some typing, I used a With block to work with the folder browser object. For those not familiar with the With block, it is an optional construct that allows you to specify an object and within the With block refer to that object's properties and methods with just ".property" or ".method". Perhaps a short example is in order:


    myObject.Color = "red"
    myObject.Material = "plastic"
    myObject.PartNumber = "12345"
    myObject.Description = "Lid"
    'the above code could be written as:
    With myObject
        .Color = "red"
        .Material = "plastic"
        .PartNumber = "12345"
        .Description = "Lid"
    End With


When working with a large number of properties and methods of a given object, the With block can save some typing and make it easier to glance through the code to see what is happening.

The .RootFolder property limits the user's selection; the user can select any subfolder within the .RootFolder, but cannot browse beyond the .RootFolder. The Desktop, the active one in the example, gives the user the most latitude in choice. From the Desktop, the user can browse to MyComputer which allows the user to choose any folder on a local or mapped network drive. Comment out the Desktop line and uncomment the MyDocuments line to see how the selection is now limited to MyDocuments or a subfolder within it. The .RootFolder must be specified from the Environment.SpecialFolder enumeration. I've included a few that looked useful, but the full list is much larger and can be found on MSDN.

The .SelectedPath property is the default folder choice presented to the user. If the user has no interaction with the dialog other than pressing the OK button, this is the directory path that will be returned. If there is a commonly used folder for the task at hand, you can make the user's experience better by pre-selecting it by using the .SelectedPath property.

The .Description property allows you to add some text near the top of the dialog page. This is a great chance to inform the user why they need to select a folder, maybe something like: "select folder for widget export". Of course, you could use this space to randomly insult the user, perhaps: "Your mother was a hampster, and your father smelt of elderberries!". Not that I'm recommending this practice, but as the programmer you have full control here.

In the If clause we call the .ShowDialog method. At this point the dialog box is onscreen awaiting the user's response. After the user presses OK, the outputFolder variable is assigned the path of the chosen folder. If the user presses Cancel, the example journal exits; but a different response may be more appropriate in your journal.

Assuming the user chose a folder and pressed OK, a few more lines of code get executed to demonstrate what we can do with this information. To check that we have the correct folder, the chosen folder is written to the listing window. Finally, we use the IO.Path.Combine method on the chosen folder and a fictional file name to build a path. The IO.Path.Combine method checks for illegal characters in the path and adds directory separator characters as necessary. If it runs into a problem it will throw an exception, production code should use a Try... Catch block to check for exceptions. There is no such check in our example code for the sake of clarity, brevity, and due to the fact that no real operations are done with the output; even should an error occur, there will be no serious consequences. For more information on IO.Path.Combine, visit MSDN.



Adding a folder browser dialog is easy to code and provides a familiar interface to the user to quickly and accurately select a folder. The code presented in this article was tested on NX8, but should run with little or no changes on any version that provides for journaling (NX3+). The .Combine method was used to build a path to a file; while this method was probably overkill for our simple example, it can provide error checking that will be important to real world uses.