Các vấn đề của bạn câu trả lời đầu tiên là nó sẽ cung cấp cho bạn kết quả WRONG nếu Dirload tải xuống mặc định đã được thay đổi thành [Download1]! Cách thích hợp để làm điều đó bao gồm tất cả khả năng là
using System;
using System.Runtime.InteropServices;
static class cGetEnvVars_WinExp {
[DllImport("Shell32.dll")] private static extern int SHGetKnownFolderPath(
[MarshalAs(UnmanagedType.LPStruct)]Guid rfid, uint dwFlags, IntPtr hToken,
out IntPtr ppszPath);
[Flags] public enum KnownFolderFlags : uint { SimpleIDList = 0x00000100
, NotParentRelative = 0x00000200, DefaultPath = 0x00000400, Init = 0x00000800
, NoAlias = 0x00001000, DontUnexpand = 0x00002000, DontVerify = 0x00004000
, Create = 0x00008000,NoAppcontainerRedirection = 0x00010000, AliasOnly = 0x80000000
}
public static string GetPath(string RegStrName, KnownFolderFlags flags, bool defaultUser) {
IntPtr outPath;
int result =
SHGetKnownFolderPath (
new Guid(RegStrName), (uint)flags, new IntPtr(defaultUser ? -1 : 0), out outPath
);
if (result >= 0) {
return Marshal.PtrToStringUni(outPath);
} else {
throw new ExternalException("Unable to retrieve the known folder path. It may not "
+ "be available on this system.", result);
}
}
}
Để kiểm tra nó, nếu bạn đặc biệt muốn tải dir cá nhân của bạn, bạn mặc định cờ false ->
using System.IO;
class Program {
[STAThread]
static void Main(string[] args) {
string path2Downloads = string.Empty;
path2Downloads =
cGetEnvVars_WinExp.GetPath("{374DE290-123F-4565-9164-39C4925E467B}", cGetEnvVars_WinExp.KnownFolderFlags.DontVerify, false);
string[] files = { "" };
if (Directory.Exists(path2Downloads)) {
files = Directory.GetFiles(path2Downloads);
}
}//Main
}
Hoặc chỉ cần một dòng [ sử dụng Environment.ExpandEnvironmentVariables()] -> (giải pháp đơn giản nhất)
using System.IO;
class Program {
[STAThread]
static void Main(string[] args) {
string path2Downloads = string.Empty;
string[] files = { "" };
path2Downloads = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Downloads");
if (Directory.Exists(path2Downloads)) {
files = Directory.GetFiles(path2Downloads);
}
}//Main
}
Nguồn
2017-10-26 18:35:01
Có cách nào để thực hiện công việc này trên Windows được bản địa hóa, trước Vista? I E. 'Path.Combine (đường dẫn," Tải xuống ");' sẽ không hoạt động, vì thư mục được gọi là 'Téléchargements', không phải' Tải xuống'. –
Bạn có thể khai thác nó ra khỏi registry ở đâu đó. Tôi không biết ở đâu, tôi đã nghỉ hưu XP từ lâu rồi. Regedit.exe rất hữu ích để tìm lại. –
Tại sao nên sử dụng 'SHGetKnownFolderPath' chứ không phải' Environment.SpecialFolder'? – Kiquenet