大家都知道,在 dotnet 裏面的可以使用 Environment.GetFolderPath 方法配合 Environment.SpecialFolder 枚舉列出當前運行環境下的一些特殊文件夾。然而 SpecialFolder 枚舉不包含對 Download 下載文件夾的枚舉值,如咱需要獲取用戶當前的下載文件夾,需要使用 Win32 方法來輔助獲取
在 dotnet 官方,已經有人提議給 SpecialFolder 添加更多的枚舉,相應的提議請參閱: https://github.com/dotnet/runtime/issues/70484
在 Windows 上,核心實現是通過 SHGetKnownFolderPath 這個 Win32 方法,先查閱文檔,定義下載文件的 Guid 值和此 Win32 方法,代碼如下
var downloadFolderGuid = new Guid("374DE290-123F-4565-9164-39C4925E467B");
[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)]
static extern string SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid id, int flags, IntPtr token);
調用方法的代碼如下
var downloadFolderPath = SHGetKnownFolderPath(downloadFolderGuid, 0, IntPtr.Zero);
完全的代碼如下
using System.Runtime.InteropServices;
var downloadFolderGuid = new Guid("374DE290-123F-4565-9164-39C4925E467B");
var downloadFolderPath = SHGetKnownFolderPath(downloadFolderGuid, 0, IntPtr.Zero);
Console.WriteLine(downloadFolderPath);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)]
static extern string SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid id, int flags, IntPtr token);
本文代碼放在 github 和 gitee 上,可以使用如下命令行拉取代碼
先創建一個空文件夾,接着使用命令行 cd 命令進入此空文件夾,在命令行裏面輸入以下代碼,即可獲取到本文的代碼
git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin 7980a73b687c430486843b81596689f809b7add0
以上使用的是 gitee 的源,如果 gitee 不能訪問,請替換爲 github 的源。請在命令行繼續輸入以下代碼,將 gitee 源換成 github 源進行拉取代碼
git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git
git pull origin 7980a73b687c430486843b81596689f809b7add0
獲取代碼之後,進入 HebeefeacuLurnaheehaja 文件夾,即可獲取到源代碼