如何在C#中为当前用户获取桌面路径?

Cri*_*scu 334 c# windows filesystems directory

如何在C#中为当前用户获取桌面路径?

我唯一能找到的是VB.NET-only类SpecialDirectories,它具有以下属性:

My.Computer.FileSystem.SpecialDirectories.Desktop
Run Code Online (Sandbox Code Playgroud)

我怎么能在C#中做到这一点?

Mar*_*ell 744

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Run Code Online (Sandbox Code Playgroud)

  • 也许您正在寻找SpecialFolder.DesktopDirectory?这是物理文件夹而不是逻辑文件夹. (7认同)
  • 如果程序以管理员身份运行,这将返回管理员用户桌面 (3认同)

小智 22

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))
 {
      Directory.CreateDirectory(filePath);
 }
Run Code Online (Sandbox Code Playgroud)

  • 不确定创建一个桌面目录是个好主意......但是对第一条路径存在的验证总是一个好主意. (7认同)
  • `Directory.CreateDirectory`在创建之前已经检查过目录是否存在,所以你的`if`语句是多余的.不确定此功能是否来自更高版本的C#,但我想我会提到它. (4认同)

小智 10

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates
Run Code Online (Sandbox Code Playgroud)