请查看下面的快照。这是从Visual Studio 2008的“新项目创建”工作流程中获取的。
此窗口用于选择存储项目的文件夹。我如何在我的C#应用程序中创建类似的窗口?
此窗口用于选择存储项目的文件夹。我如何在我的C#应用程序中创建类似的窗口?
这类功能在Office中也有,它是一个对话框,允许选择文件夹。唯一的区别是选择文件夹的按钮名字是“确定”而不是“选择文件夹”。
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<string>().ToArray();
if (selectedFolders.Length > 0)
{
string selectedFolder = selectedFolders[0];
}
}
var directoryDialog = new CommonOpenFileDialog
{
IsFolderPicker = true,
Title = "Select Folder"
};
我将代码从C#修改为VB,我的环境是VS2015 + Office 2010。我的代码与Daniel的略有不同,因为Daniel的一些函数仅支持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
请查看BetterFolderBrowser。它提供了您所需的一切,还有更多。
BetterFolderBrowser是一个.NET组件库,旨在帮助开发人员通过使用类似于标准OpenFileDialog的浏览器对话框来代替当前的FolderBrowserDialog,从而为用户提供更好的文件夹浏览和选择体验。后者只允许使用树形视图显示格式进行单个文件夹选择。这使得使用标准Windows资源管理器对话框进行查看、修改、搜索和选择体验更加轻松。
SaveFileDialog
并插入了零宽空格符号作为文件名。然后我只需使用Path.GetFullPath
剥离路径即可。 - Hi-Angel