[尝试使用SHGetKnownFolderPath API返回VB.Net中Downloads文件夹的路径。我能够调用该函数并获得指向结果的指针,但是我迷惑了将其转换为VB.Net字符串以供使用的正确方法。 (我知道CopyMemory不是要走的路,但我似乎无法理解编组方法)。
<>
Imports System.Runtime.InteropServices
<DllImport("shell32.dll")>
Private Function SHGetKnownFolderPath(
<MarshalAs(UnmanagedType.LPStruct)> ByVal rfid As Guid,
ByVal dwFlags As UInt32,
ByVal hToken As IntPtr,
ByRef pszPath As IntPtr) As Int32
End Function
Public Function GetDownloadsFolder() As String
Dim Result As String = ""
Dim ppszPath As IntPtr
Dim gGuid As Guid = New Guid("{374DE290-123F-4565-9164-39C4925E467B}")
If SHGetKnownFolderPath(gGuid, 0, 0, ppszPath) = 0 Then
' ----
' Question was: what goes here? Answer follows:
'
Result = Marshal.PtrToStringUni(ppszPath)
Marshal.FreeCoTaskMem(ppszPath)
' ---
End If
Return Result
End Function
Alex F因提供关键信息而获得赞誉-这是最终代码:
Imports System.Runtime.InteropServices
<DllImport("shell32.dll")>
Private Function SHGetKnownFolderPath(
<MarshalAs(UnmanagedType.LPStruct)> ByVal rfid As Guid,
ByVal dwFlags As UInt32,
ByVal hToken As IntPtr,
ByRef pszPath As IntPtr) As Int32
End Function
Public Function GetDownloadsFolder() As String
Dim Result As String = ""
Dim ppszPath As IntPtr
Dim gGuid As Guid = New Guid("{374DE290-123F-4565-9164-39C4925E467B}")
If SHGetKnownFolderPath(gGuid, 0, 0, ppszPath) = 0 Then
Result = Marshal.PtrToStringUni(ppszPath)
Marshal.FreeCoTaskMem(ppszPath)
End If
Return Result
End Function