文件夹浏览器对话框,如打开文件

请参阅下面的快照。 这取自Visual Studio 2008中的“新项目创建”工作流程。

该窗口用于选择将存储项目的文件夹。 如何在c#应用程序中创建类似的窗口?

在此处输入图像描述

它在Office中类似,这是一个允许选择文件夹的对话框。 唯一的区别是Select文件夹按钮名为“OK”而不是“Select folder”。

 Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Core.FileDialog fileDialog = app.get_FileDialog(Microsoft.Office.Core.MsoFileDialogType.msoFileDialogFolderPicker); fileDialog.InitialFileName = "c:\\Temp\\"; //something you want int nres = fileDialog.Show(); if (nres == -1) //ok { Microsoft.Office.Core.FileDialogSelectedItems selectedItems = fileDialog.SelectedItems; string[] selectedFolders = selectedItems.Cast().ToArray(); if (selectedFolders.Length > 0) { string selectedFolder = selectedFolders[0]; } } 

当然,您需要添加对Microsoft.Office.Core(Microsoft Office 14.0对象库)和Microsoft.Office.Interop.Excel(Microsoft Excel 14.0对象库)的引用。

我找到了一篇关于默认FolderBrowserDialog及其局限性的文章: http : //www.ssware.com/articles/folderbrowserdialog-unmasked-everything-you-wanted-to-know-about-the-folder-browser-component-from -dotnet-framework.htm

来自ssware的第三方组件“Shell MegaPack”( http://www.ssware.com/megapack.htm )为WinForms,ASP.net和WPF提供了类似Windows浏览器的文件和文件夹浏览器控件。

我将代码从C#修改为VB,我的环境是VS2015 + Office 2010.我的代码与Daniel的代码略有不同,因为Daniel的代码中的某些function仅支持Office 2003/2007

通过使用新的excel实例,它将比打开OpenFileDialog或OpenFolderDialog慢,但它更方便用户。 我的程序只调用一次这个代码,因此在我的情况下,为了用户友好性而牺牲性能并不是一个问题。

 Imports Microsoft.Office Imports Excel = Microsoft.Office.Interop.Excel Private Sub Button_select_raw_dir_Click(sender As Object, e As EventArgs) Handles Button_select_raw_dir.Click Dim raw_app As Excel.Application = New Excel.Application Dim raw_data_open_folder_dialog As Microsoft.Office.Core.FileDialog raw_data_open_folder_dialog = raw_app.FileDialog(Microsoft.Office.Core.MsoFileDialogType.msoFileDialogFolderPicker) raw_data_open_folder_dialog.AllowMultiSelect = False raw_data_open_folder_dialog.Title = "Please select the raw data's dir " Dim nres As Integer = raw_data_open_folder_dialog.Show() Dim sz_SelectedPath As String = Nothing If nres = -1 Then '-1 means open... lol For Each selectedItems As Object In raw_data_open_folder_dialog.SelectedItems sz_SelectedPath = selectedItems.ToString() Next TextBox_raw_data_dir.Text = sz_SelectedPath End If raw_app.Quit() ReleaseComObject(raw_app) GC.Collect() GC.WaitForPendingFinalizers() End Sub ' Release excel objects to avoid memory leak Public Sub ReleaseComObject(ByRef obj As Object) Try System.Runtime.InteropServices.Marshal.ReleaseComObject(obj) obj = Nothing Catch ex As Exception obj = Nothing MsgBox("Exception! Failed to release com obj, debug your code.") End Try End Sub 

如果你想要一个C#版本,我相信你足够智能将它移植到C#:)

如果你可以添加一个nuget包,Microsoft.WindowsAPICodePack.Shell有一个CommonOpenFileDialog可以在“文件夹模式”中使用,它应该符合你想要的用法。

 var directoryDialog = new CommonOpenFileDialog { IsFolderPicker = true, Title = "Select Folder" };