In order to get the Downloads directory path in C# properly, some developers could just use a fixed path in a string like "C:\Users\username\Downloads"
especially when the application is private. However, if you are planning on launching your application publicly, there's a good chance that some users may use a different directory for the Downloads path.
Surprisingly, the downloads directory path cannot be obtained through the EnvironmentFolders.GetPath
method and Environment.SpecialFolders
enum. So what should we do now? We will use the SHGetKnownFolderPath
function available in the Legacy Windows Environment Features (shlobj_core.h header). This method allows you to retrieve the full path of a known folder identified by the folder's KNOWNFOLDERID. The KNOWNFOLDERID constant represents a GUID that identifies a standard folder registered with the system as Known Folders. These folders are installed with Windows Vista and later operating systems, and a computer will have only folders appropriate to it installed.
In our case, the Downloads folder path is the one we are trying to obtain and the KNOWNFOLDERID of the Downloads folder is 374DE290-123F-4565-9164-39C4925E467B
. Having that, we can proceed with the implementation to obtain the Downloads path.
The following code snippet should do the trick:
Form example
The following full example should help you to understand the context of where to place every line of code in your own project:
Happy coding ❤️!
0 Comments