Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

c# - How do I determine the Windows 'Download folder' path?

On my machine, it's here:

string downloadsPath = Path.Combine(
   Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
   "Downloads");

But on a colleagues machine, this folder doesnt exist, and his Downloads folder is in his 'My Documents' folder. We are both on Windows 7*.

*Edit: in fact, it turns out he was not running the app on his own machine but a Windows Server 2003 machine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Windows does not define a CSIDL for the Downloads folder and it is not available through the Environment.SpecialFolder enumeration.

However, the new Vista Known Folder API does define it with the ID of FOLDERID_Downloads. Probably the easiest way to obtain the actual value is to P/invoke SHGetKnownFolderPath.

public static class KnownFolder
{
    public static readonly Guid Downloads = new Guid("374DE290-123F-4565-9164-39C4925E467B");
}

[DllImport("shell32.dll", CharSet=CharSet.Unicode)]
static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out string pszPath);

static void Main(string[] args)
{
    string downloads;
    SHGetKnownFolderPath(KnownFolder.Downloads, 0, IntPtr.Zero, out downloads);
    Console.WriteLine(downloads);
}

Note that the P/invoke given on pinvoke.net is incorrect since it fails to use Unicode character set. Also I have taken advantage of the fact that this API returns memory allocated by the COM allocator. The default marshalling of the P/invoke above is to free the returned memory with CoTaskMemFree which is perfect for our needs.

Be careful that this is a Vista and up API and do not attempt to call it on XP/2003 or lower.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...