In .NET, we can retrieve the paths to 'special folders', like Documents / Desktop etc. Today I tried to find a way to get the path to the 'Downloads' folder, but it's not special enough it seems.
I know I can just do 'C:\Users\Username\Downloads', but that seems an ugly solution. So how can I retrieve the path using .NET?
By default, Chrome, Firefox and Microsoft Edge download files to the Downloads folder located at %USERPROFILE%\Downloads. USERPROFILE is a variable that refers to the logged in user's profile directory on the Windows computer, e.g. the path may look like C:\Users\YourUserName\Downloads.
To find downloads on your PC: Select File Explorer from the taskbar, or press the Windows logo key + E. Under Quick access, select Downloads.
Yes it is special, discovering the name of this folder didn't become possible until Vista. .NET still needs to support prior operating systems. You can pinvoke SHGetKnownFolderPath() to bypass this limitation, like this:
using System.Runtime.InteropServices; ... public static string GetDownloadsPath() { if (Environment.OSVersion.Version.Major < 6) throw new NotSupportedException(); IntPtr pathPtr = IntPtr.Zero; try { SHGetKnownFolderPath(ref FolderDownloads, 0, IntPtr.Zero, out pathPtr); return Marshal.PtrToStringUni(pathPtr); } finally { Marshal.FreeCoTaskMem(pathPtr); } } private static Guid FolderDownloads = new Guid("374DE290-123F-4565-9164-39C4925E467B"); [DllImport("shell32.dll", CharSet = CharSet.Auto)] private static extern int SHGetKnownFolderPath(ref Guid id, int flags, IntPtr token, out IntPtr path);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With