从VB.Net中的SHGetKnownFolderPath返回路径

问题描述 投票:0回答:1

[尝试使用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
vb.net marshalling
1个回答
0
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.