Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically derive Windows Downloads folder "%USERPROFILE%/Downloads"?

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?

like image 981
Maestro Avatar asked Sep 25 '10 18:09

Maestro


People also ask

How do I find the download location of a file?

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.

How do I find Windows 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.


1 Answers

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); 
like image 70
Hans Passant Avatar answered Sep 25 '22 20:09

Hans Passant