C# 如何确定窗口';下载文件夹';路径

C# 如何确定窗口';下载文件夹';路径,c#,windows,C#,Windows,在我的机器上,它在这里: string downloadsPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"); 但是在同事的机器上,这个文件夹不存在,他的下载文件夹在他的“我的文档”文件夹中。我们都在Windows7*上 *编辑:事实上,他不是在自己的计算机上运行应用程序,而是在Windows Server 2003计算机上运行应用程序

在我的机器上,它在这里:

string downloadsPath = Path.Combine(
   Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
   "Downloads");
但是在同事的机器上,这个文件夹不存在,他的下载文件夹在他的“我的文档”文件夹中。我们都在Windows7*上

*编辑:事实上,他不是在自己的计算机上运行应用程序,而是在Windows Server 2003计算机上运行应用程序。

Windows没有为下载文件夹定义应用程序,并且无法通过枚举使用该应用程序

但是,新的Vista API确实使用ID定义了它。获取实际值的最简单方法可能是P/invoke

请注意,pinvoke.net上提供的p/invoke不正确,因为它无法使用Unicode字符集。我还利用了这个API返回COM分配器分配的内存这一事实。上面P/invoke的默认编组是使用
CoTaskMemFree
释放返回的内存,这非常适合我们的需要

请注意,这是一个Vista和up API,不要试图在XP/2003或更低版本上调用它

您可以使用

参考:Microsoft.WindowsAPICodePack.Shell.dll

需要以下命名空间:

使用Microsoft.WindowsAPICodePack.Shell;
简单用法:

string downloadsPath=KnownFolders.Downloads.Path;

我使用的VB.Net函数如下

<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

“下载”文件夹已本地化。对于非英语系统,它不称为“下载”…在windows 7下,下载文件夹是一个特殊的文件夹,这样我就可以将其移动到我想要的任何特定位置。与移动“我的文档”文件夹等的方式相同。@Daan对此没有任何限制,因此它在这种方式上并不特殊。@Daan但它被定义为已知文件夹。我在查找旧的CSIDL列表。似乎是真的,但它被称为KNOWNFOLDERID:FOLDERID\u下载似乎您已经找到/回答了该部分。@Daan是的,已知文件夹取代了CSIDL,据我所知,CSIDL现在已被弃用。
<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
    Dim sDownloadFolder = GetDownloadsFolder()
    Dim di = New DirectoryInfo(sDownloadFolder)

    'Move all CSV files that begin with BE in specific folder
    'that has been defined in a CONFIG file (variable: sExtractPath

    For Each fi As FileInfo In di.GetFiles("BE*.csv")
        Dim sFilename = sExtractPath & "\" & fi.Name
        File.Move(fi.FullName, sFilename)
    Next