New object system windows forms openfiledialog

some tips useful to keep in mind. Contribute to myusefulrepo/Tips development by creating an account on GitHub.

How to create an open file and folder dialog box with PowerShell

How to create an open file dialog box with PowerShell

1 — load the .NET System.Windows.Forms assembly

Add-Type -AssemblyName System.Windows.Forms

2 — Instantiate an OpenFileDialog object using New-Object

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @< InitialDirectory = [Environment]::GetFolderPath('Desktop') >

You can see above that the OpenFileDialog class constructor has an InitialDirectory argument.
This tells the OpenFileDialog class which folder to display when the dialog box comes up.
In this case, I have the dialog box to display the desktop.
At this point, the dialog box will not display. We’re just instantiating the object.
To show the dialog box, we’ll have to use the ShowDialog() method.

3 — Show the dialog box

$Null = $FileBrowser.ShowDialog()

4 — limit the input by file type too using the Filter property

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @< InitialDirectory = [Environment]::GetFolderPath('Desktop') Filter = 'Documents (*.docx)|*.docx|SpreadSheet (*.xlsx)|*.xlsx' > $Null = $FileBrowser.ShowDialog()

5 — OpenFile Dialog bow in a function : Allow filter on one file extension

function Get-FileName($InitialDirectory) < $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog $OpenFileDialog.InitialDirectory = $InitialDirectory $OpenFileDialog.filter = "CSV (*.csv) | *.csv" $OpenFileDialog.ShowDialog() | Out-Null $OpenFileDialog.FileName >

6 — OpenFile Dialog bow in a function : Allow multiple filters

function Get-FileName($InitialDirectory) < $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog $OpenFileDialog.InitialDirectory = $InitialDirectory $OpenFileDialog.filter = "Documents (*.docx)|*.docx |SpreadSheet (*.xlsx)|*.xlsx" $OpenFileDialog.ShowDialog() | Out-Null $OpenFileDialog.FileName >

[Nota] : As we can see, the filter applies for one or the other of the selected extensions, not both at the same time

FINALLY : OpenFile Dialog bow in a function : Allow multiple filters and multiple selections and manage errors

function Get-FileName <  .SYNOPSIS Show an Open File Dialog and return the file selected by the user .DESCRIPTION Show an Open File Dialog and return the file selected by the user .PARAMETER WindowTitle Message Box title Mandatory - [String] .PARAMETER InitialDirectory Initial Directory for browsing Mandatory - [string] .PARAMETER Filter Filter to apply Optional - [string] .PARAMETER AllowMultiSelect Allow multi file selection Optional - switch  .EXAMPLE Get-FileName cmdlet Get-FileName at position 1 of the command pipeline Provide values for the following parameters: WindowTitle: My Dialog Box InitialDirectory: c:temp C:Temp42258.txt No passthru paramater then function requires the mandatory parameters (WindowsTitle and InitialDirectory) .EXAMPLE Get-FileName -WindowTitle MyDialogBox -InitialDirectory c:temp C:Temp41553.txt Choose only one file. All files extensions are allowed .EXAMPLE Get-FileName -WindowTitle MyDialogBox -InitialDirectory c:temp -AllowMultiSelect C:Temp8544.txt C:Temp42258.txt Choose multiple files. All files are allowed .EXAMPLE Get-FileName -WindowTitle MyDialogBox -InitialDirectory c:temp -AllowMultiSelect -Filter "text file (*.txt) | *.txt" C:TempAES_PASSWORD_FILE.txt Choose multiple files but only one specific extension (here : .txt) is allowed .EXAMPLE Get-FileName -WindowTitle MyDialogBox -InitialDirectory c:temp -AllowMultiSelect -Filter "Text files (*.txt)|*.txt| csv files (*.csv)|*.csv | log files (*.log) | *.log" C:Templogrobo.log C:Tempmylogfile.log Choose multiple file with the same extension .EXAMPLE Get-FileName -WindowTitle MyDialogBox -InitialDirectory c:temp -AllowMultiSelect -Filter "selected extensions (*.txt, *.log) | *.txt;*.log" C:TempIPAddresses.txt C:Templog.log Choose multiple file with different extensions Nota :It's important to have no white space in the extension name if you want to show them .EXAMPLE Get-Help Get-FileName -Full .INPUTS System.String System.Management.Automation.SwitchParameter .OUTPUTS System.String .NOTESs Version : 1.0 Author : O. FERRIERE Creation Date : 11/09/2019 Purpose/Change : Initial development Based on different pages : mainly based on https://blog.danskingdom.com/powershell-multi-line-input-box-dialog-open-file-dialog-folder-browser-dialog-input-box-and-message-box/ https://code.adonline.id.au/folder-file-browser-dialogues-powershell/ https://thomasrayner.ca/open-file-dialog-box-in-powershell/ #> [CmdletBinding()] [OutputType([string])] Param ( # WindowsTitle help description [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = "Message Box Title", Position = 0)] [String]$WindowTitle, # InitialDirectory help description [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = "Initial Directory for browsing", Position = 1)] [String]$InitialDirectory, # Filter help description [Parameter( Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = "Filter to apply", Position = 2)] [String]$Filter = "All files (*.*)|*.*", # AllowMultiSelect help description [Parameter( Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = "Allow multi files selection", Position = 3)] [Switch]$AllowMultiSelect ) # Load Assembly Add-Type -AssemblyName System.Windows.Forms # Open Class $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog # Define Title $OpenFileDialog.Title = $WindowTitle # Define Initial Directory if (-Not [String]::IsNullOrWhiteSpace($InitialDirectory)) < $OpenFileDialog.InitialDirectory = $InitialDirectory > # Define Filter $OpenFileDialog.Filter = $Filter # Check If Multi-select if used if ($AllowMultiSelect) < $OpenFileDialog.MultiSelect = $true > $OpenFileDialog.ShowHelp = $true # Without this line the ShowDialog() function may hang depending on system configuration and running from console vs. ISE. $OpenFileDialog.ShowDialog() | Out-Null if ($AllowMultiSelect) < return $OpenFileDialog.Filenames > else < return $OpenFileDialog.Filename > >

How to create an open folder dialog box with PowerShell

1 — load the .NET System.Windows.Forms assembly

Add-Type -AssemblyName System.Windows.Forms

2 — Instantiate an FolderBrowserDialog object using New-Object

$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog

3 — Show the dialog box

$Null = $FolderBrowser.ShowDialog()

4 — limit the input by file type too using the Filter property

$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @< RootFolder = "MyComputer" Description = "$Env:ComputerName - Select a folder" > $Null = $FolderBrowser.ShowDialog()

FINALLY — Open Folder Browser as a function

Function Get-FolderName <  .SYNOPSIS Show a Folder Browser Dialog and return the directory selected by the user .DESCRIPTION Show a Folder Browser Dialog and return the directory selected by the user .PARAMETER SelectedPath Initial Directory for browsing Mandatory - [string] .PARAMETER Description Message Box Title Optional - [string] - Default : "Select a Folder" .PARAMETER ShowNewFolderButton Show New Folder Button when unused (default) or doesn't show New Folder when used with $false value Optional - [Switch]  .EXAMPLE Get-FolderName cmdlet Get-FileFolder at position 1 of the command pipeline Provide values for the following parameters: SelectedPath: C:temp C:Temp Choose only one Directory. It's possible to create a new folder (default) .EXAMPLE Get-FolderName -SelectedPath c:temp -Description "Select a folder" -ShowNewFolderButton C:TempTest Choose only one Directory. It's possible to create a new folder .EXAMPLE Get-FolderName -SelectedPath c:temp -Description "Select a folder" C:TempTest Choose only one Directory. It's not possible to create a new folder .EXAMPLE Get-FolderName -SelectedPath c:temp C:TempTest Choose only one Directory. It's possible to create a new folder (default) .EXAMPLE Get-Help Get-FolderName -Full .INPUTS System.String System.Management.Automation.SwitchParameter .OUTPUTS System.String .NOTES Version : 1.0 Author : O. FERRIERE Creation Date : 12/10/2019 Purpose/Change : Initial development Based on different pages : mainly based on https://blog.danskingdom.com/powershell-multi-line-input-box-dialog-open-file-dialog-folder-browser-dialog-input-box-and-message-box/ https://code.adonline.id.au/folder-file-browser-dialogues-powershell/ https://thomasrayner.ca/open-file-dialog-box-in-powershell/ https://code.adonline.id.au/folder-file-browser-dialogues-powershell/ #> [CmdletBinding()] [OutputType([string])] Param ( # InitialDirectory help description [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = "Initial Directory for browsing", Position = 0)] [String]$SelectedPath, # Description help description [Parameter( Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = "Message Box Title")] [String]$Description="Select a Folder", # ShowNewFolderButton help description [Parameter( Mandatory = $false, HelpMessage = "Show New Folder Button when used")] [Switch]$ShowNewFolderButton ) # Load Assembly Add-Type -AssemblyName System.Windows.Forms # Open Class $FolderBrowser= New-Object System.Windows.Forms.FolderBrowserDialog # Define Title $FolderBrowser.Description = $Description # Define Initial Directory if (-Not [String]::IsNullOrWhiteSpace($SelectedPath)) < $FolderBrowser.SelectedPath=$SelectedPath > if($folderBrowser.ShowDialog() -eq "OK") < $Folder += $FolderBrowser.SelectedPath > return $Folder >

The open file/folder dialog box is a great way to receive input for your scripts interactively. It provides a file browser that makes for a much more user-friendly approach than merely prompting for a path. In this post I show you how can use OpenFileDialog in your PowerShell scripts.

  • Author
  • Recent Posts

Adam Bertram is a 20-year IT veteran, Microsoft MVP, blogger, and trainer.

When you’re using a Windows application and need to provide input for a file or folder, you’ve probably seen the standard open file dialog.

Open file dialog

Open file dialog

This dialog box is standard across lots of Windows applications. The software you’re using to invoke this dialog box uses a .NET assembly called System.Windows.Forms with a class inside called OpenFileDialog. Did you know you can get input to your PowerShell scripts this way too? Since PowerShell lies directly on top of .NET, we can invoke any .NET class we need, which means we can also bring up the open file dialog box.

To do this, we’ll first need to load the System.Windows.Forms assembly manually using the Add-Type cmdlet. Lots of .NET assemblies are typically loaded for you, but in this case, we have to do it manually.

Add-Type -AssemblyName System.Windows.Forms

Once we’ve loaded the assembly, we can instantiate an OpenFileDialog object using New-Object.

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @

You can see above that the OpenFileDialog class constructor has an InitialDirectory argument. This tells the OpenFileDialog class which folder to display when the dialog box comes up. In this case, I have the dialog box to display the desktop.

At this point, the dialog box will not display. We’re just instantiating the object. To show the dialog box, we’ll have to use the ShowDialog() method.

$null = $FileBrowser.ShowDialog()

This will display the dialog box. I’m assigning the output of ShowDialog() to $null. This is because the output does not return anything useful for our purposes. You might expect the output to return the chosen file name, but it doesn’t. The system then stores the file information in the OpenFileDialog object itself.

PS C:> $FileBrowser CheckFileExists : True Multiselect : False ReadOnlyChecked : False ShowReadOnly : False SafeFileName : Thumbs.db SafeFileNames : AddExtension : True CheckPathExists : True DefaultExt : DereferenceLinks : True FileName : \MacHomeDesktopThumbs.db FileNames : <\MacHomeDesktopThumbs.db>Filter : FilterIndex : 0 InitialDirectory : \MacHomeDesktop RestoreDirectory : False ShowHelp : False SupportMultiDottedExtensions : False Title : ValidateNames : True CustomPlaces : <> AutoUpgradeEnabled : True Tag : Site : Container :

You can see above that the OpenFileDialog object now contains all the information gathered from the file chosen.

The above example allows me to choose any file we’d like, but we also can limit the input by file type too using the Filter property.

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @ < InitialDirectory = [Environment]::GetFolderPath('Desktop') Filter = 'Documents (*.docx)|*.docx|SpreadSheet (*.xlsx)|*.xlsx' >$null = $FileBrowser.ShowDialog()

Now when the dialog box displays, you can see below that the only options are to choose between Word and Excel documents.

Subscribe to 4sysops newsletter!

Filtering by file

Filtering by file

For more information about this method of receiving file location input from users, refer to the Microsoft MSDN information.

Note: This tip requires PowerShell 2.0 or above.

In PowerShell, it is possible to use GUI elements to request user input. Although it is possible to create your own forms from scratch, there are also many useful pre-built dialogs available. In this tip, I will show you how to use the System.Windows.Forms.OpenFileDialog to select one or multiple files.

The following code will open a window that will prompt the user to select a single file. By setting the InitialDirectory property, the starting directory will be set to the current user’s desktop. This is done by using the [Environment] Desktop special folder:

Add-Type -AssemblyName System.Windows.Forms $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @ < InitialDirectory = [Environment]::GetFolderPath('Desktop') >[void]$FileBrowser.ShowDialog() $FileBrowser.FileNames 

If documents need to be selected, it can be useful to set the starting folder to the documents folder. By setting a filter, we can ensure that only a certain type of file is selected. The next code sample will allow users to select .docx files. The filter can be changed by the user to also select an xlsx file:

Add-Type -AssemblyName System.Windows.Forms $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @ < InitialDirectory = [Environment]::GetFolderPath('MyDocuments') Filter = 'Documents (*.docx)|*.docx|SpreadSheet (*.xlsx)|*.xlsx' >[void]$FileBrowser.ShowDialog() $FileBrowser.FileNames

To select multiple files the MultiSelect property should be set to True.

Add-Type -AssemblyName System.Windows.Forms $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @ < Multiselect = $true >[void]$FileBrowser.ShowDialog() $FileBrowser.FileNames 

For more information about this class the following MSDN article can be used:

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#

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#

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#

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. MessageBox.Show(file);
  4. >

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#

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#

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. OpenFileDialog openFileDialog1 = new OpenFileDialog
  3. InitialDirectory = @ «D:» ,
  4. Title = «Browse Text Files» ,
  5. CheckFileExists = true ,
  6. CheckPathExists = true ,
  7. DefaultExt = «txt» ,
  8. Filter = «txt files (*.txt)|*.txt» ,
  9. FilterIndex = 2,
  10. RestoreDirectory = true ,
  11. ReadOnlyChecked = true ,
  12. ShowReadOnly = true
  13. >;
  14. if (openFileDialog1.ShowDialog() == DialogResult.OK)
  15. textBox1.Text = openFileDialog1.FileName;
  16. >
  17. >

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

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

The output looks like Figure 6.

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.

When I run the following, PowerShell hangs waiting for the dialog to close, even though the dialog is never displayed:

[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowDialog( ) 

Calling ShowDialog on a Windows.Forms.Form works fine. I also tried creating a Form and passing it as the parent to $d.ShowDialog , but the result was no different.

asked Oct 19, 2008 at 17:32

Emperor XLII Emperor XLII

12.8k 11 gold badges 69 silver badges 74 bronze badges

I was able to duplicate your problem and found a workaround. I don’t know why this happens, but it has happened to others.

If you set the ShowHelp property to $true, you will get the dialog to come up properly.

[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowHelp = $true $d.ShowDialog( ) 

answered Oct 19, 2008 at 17:57

It appears to me that the dialog is actually opening just fine, but it’s behind the powershell console window. Unfortunately it doesn’t show in the taskbar, so there’s no indication that it’s there unless you move the powershell window or Alt+Tab. It also appears that the ShowHelp workaround didn’t have any effect for me.

EDIT Here’s a way to do do it using your secondary-form idea. The basic idea is to create a new form which opens the OpenFileDialog from inside its Shown event. The key is calling Activate on the form before opening the dialog, so that the form comes to the front and the dialog appears. I moved the form offscreen by setting the Location to an offscreen value, but you could alternatively set Form.Visible = $false from inside the Shown event.

[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $ofn = New-Object System.Windows.Forms.OpenFileDialog $outer = New-Object System.Windows.Forms.Form $outer.StartPosition = [Windows.Forms.FormStartPosition] "Manual" $outer.Location = New-Object System.Drawing.Point -100, -100 $outer.Size = New-Object System.Drawing.Size 10, 10 $outer.add_Shown( < $outer.Activate(); $ofn.ShowDialog( $outer ); $outer.Close(); >) $outer.ShowDialog() 

answered Oct 19, 2008 at 18:22

43.7k 4 gold badges 43 silver badges 68 bronze badges