2013-07-10 33 views
3

我在VB.NET中调用Shell.BrowseForFolder,因为我需要在rootFolder参数中传递任意路径。所以,我实例化一个像这样的客体:InvokeMember给出与直接调用不同的结果

Dim shellType As Type = Type.GetTypeFromProgID("Shell.Application") 
Dim shell = Activator.CreateInstance(shellType) 

然后我打电话:

Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder) 

它不按预期工作(根文件夹F:不使用)

Direct call

但是如果我使用具有相同参数的反射:

Dim folder = shellType.InvokeMember("BrowseForFolder", _ 
    BindingFlags.InvokeMethod, Nothing, shell, New Object() {0, message, &H241, _ 
    rootFolder}) 

它的工作原理!

Reflection

但对我来说,2个呼叫(InvokeMember和直接调用)应该产生类似的结果(参数是相同的)。发生了什么?

编辑:

事实上,它的工作原理,如果我调用toString(),或者如果我把一个litteral:

Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder.ToString()) 

Dim folder = shell.BrowseForFolder(0, message, &H241, "F:") 

但事实并非如此如果rootFolder是参数,则工作,例如:

Function BrowseForFolder(ByVal message As String, ByVal rootFolder As String) As String 
    Dim shellType As Type = Type.GetTypeFromProgID("Shell.Application") 
    Dim shell = Activator.CreateInstance(shellType) 
    Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder) 
    If folder Is Nothing Then 
     Return "" 
    End If 
    Return folder.Self.Path 
End Function 

回答

2

只有在Windows 7 64位下使用vs 2012重现此问题的唯一方法是在该变量中有一个无效的rootFolder,类似于空字符串或废话数据。

你可以做一个断点在该行:

Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder) 

和检查什么是rootFolder

找到一种方法试试这个;

Dim folder = shell.BrowseForFolder(0, message, &H241, rootFolder.ToString()) 

我的代码:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    Dim rootFolder As Object = "f:" 
    Dim shellType As Type = Type.GetTypeFromProgID("Shell.Application") 
    Dim shell = Activator.CreateInstance(shellType) 
    Dim folder = shell.BrowseForFolder(0, "message", &H241, rootFolder.ToString()) 
End Sub 
+0

同意,不能在vs2010上重现,同样的操作系统。 – RobS

+0

我在Windows 7 64位操作系统上使用VS 2010。 rootFolder是一个用“F:”初始化的字符串。该磁盘存在于我的电脑上。 – Maxence

+0

@Maxence,我想我找到了解决方法,我能够重现问题 – Fredou

1

你总是可以直接使用的FolderBrowserDialog:

Dim f As New FolderBrowserDialog 
f.SelectedPath = "f:" 
f.ShowDialog() 

虽然我不能看到如何得到它显示F:

+0

我正在使用Shell.BrowseForFolder,因为FolderBrowserDialog只在他的RootFolder属性中使用SpecialFolder。 – Maxence

+0

当然 - 毕竟,这是一个奇怪的限制。 – RobS

相关问题