简体   繁体   English

获取C#中主目录的路径?

[英]Getting the path of the home directory in C#?

Okay, I've checked Environment.SpecialFolder, but there's nothing in there for this.好的,我已经检查了 Environment.SpecialFolder,但是里面没有任何东西。

I want to get the home directory of the current user in C#. (eg c:\documents and settings\user under XP, c:\users\user under Vista, and /home/user under Unix.)我想获取C#中当前用户的主目录。(如XP下c:\documents and settings\user ,Vista下c:\users\user ,Unix下/home/user

I know I can read enviroment variables to find this out, but I want to do this in a cross-platform way.我知道我可以读取环境变量来找出答案,但我想以跨平台的方式进行。

Is there any way I can do this with .NET (preferably using mscorlib)?有什么办法可以用 .NET 做到这一点(最好使用 mscorlib)?

UPDATE : Okay, this is the code I ended up using:更新:好的,这是我最终使用的代码:

string homePath = (Environment.OSVersion.Platform == PlatformID.Unix || 
                   Environment.OSVersion.Platform == PlatformID.MacOSX)
    ? Environment.GetEnvironmentVariable("HOME")
    : Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");

You are looking for Environment.SpecialFolder.UserProfile which refers to C:\\Users\\myname on Windows and /home/myname on Unix/Linux:您正在寻找Environment.SpecialFolder.UserProfile ,它指的是 Windows 上的C:\\Users\\myname和 Unix/Linux 上的/home/myname

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)

Note that Environment.SpecialFolder.Personal is My Documents (or Documents in win7 and above), but same as home directory on Unix/Linux.注意Environment.SpecialFolder.Personal是我的文档(或在 win7 及以上版本的文档),但与 Unix/Linux 上的主目录相同。

Environment.SpecialFolder.Personal doesn't actually return the home folder, it returns the My Documents folder. Environment.SpecialFolder.Personal实际上并不返回主文件夹,而是返回我的文档文件夹。 The safest way to get the home folder on Win32 is to read %HOMEDRIVE%%HOMEPATH% .在 Win32 上获取主文件夹的最安全方法是读取%HOMEDRIVE%%HOMEPATH% Reading environment variables is actually very portable to do (across Unix and Windows), so I'm not sure why the poster wanted to not do it.阅读环境变量其实是非常移植到(在UNIX和Windows)做的,所以我不知道为什么海报想那么做。

Edited to add: For crossplatform (Windows/Unix) C#, I'd read $HOME on Unix and OSX and %HOMEDRIVE%%HOMEPATH% on Windows.编辑添加:对于跨平台(Windows/Unix)C#,我会在 Unix 和 OSX 上阅读$HOME以及在 Windows 上阅读%HOMEDRIVE%%HOMEPATH%

I believe what you are looking for is:我相信你正在寻找的是:

System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)

For reference, it is infact contained in mscorlib .作为参考,它实际上包含在mscorlib

In DotNetCore 1.1 System.Environment.SpecialFolder does not exist.在 DotNetCore 1.1 System.Environment.SpecialFolder中不存在。 It might exist in 2.0-beta.它可能存在于 2.0-beta 中。 Until then, to do this you can use the following:在此之前,您可以使用以下方法:

var envHome = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "HOMEPATH" : "HOME";
var home = Environment.GetEnvironmentVariable(envHome);`

The bottom line answer is No. The is no simple System based method in .NET to get the Home directory such that we could expect an implementation in both .NET on Windows and in Mono.底线答案是否定的。 .NET 中没有简单的基于系统的方法来获取主目录,因此我们可以期望在 Windows 和 Mono 上的 .NET 中实现。

You will need to do some OS detection and branch to OS specific code.您将需要进行一些操作系统检测并分支到操作系统特定的代码。

When you say cross-platform way, what other OSs do you need to support?当您说跨平台方式时,您还需要支持哪些其他操作系统? You may need to do some simple OS detection to select the method for finding the home directory if you're running on a non-Windows OS.如果您在非 Windows 操作系统上运行,您可能需要进行一些简单的操作系统检测来选择查找主目录的方法。

This website seems to give a way to do what you need in Windows.该网站似乎提供了一种在 Windows 中执行所需操作的方法。

This can be done using GetEnvironmentVariable in System.IO :这可以使用System.IO GetEnvironmentVariable来完成:

public string GetUserHome() {
    var homeDrive = Environment.GetEnvironmentVariable("HOMEDRIVE");
    if (!string.IsNullOrWhiteSpace(homeDrive))
    {
        var homePath = Environment.GetEnvironmentVariable("HOMEPATH");
        if (!string.IsNullOrWhiteSpace(homePath))
        {            
            var fullHomePath = homeDrive + Path.DirectorySeparatorChar + homePath;
            return Path.Combine(fullHomePath, "myFolder");
        }
        else
        {
            throw new Exception("Environment variable error, there is no 'HOMEPATH'");
        }
    }
    else
    {
        throw new Exception("Environment variable error, there is no 'HOMEDRIVE'");
    }
}

Then it produces under windows: C:\\\\\\\\Users\\\\myusername\\\\myFolder然后它在windows下产生: C:\\\\\\\\Users\\\\myusername\\\\myFolder

Note that if you use请注意,如果您使用

var fullHomePath = Path.Combine(homeDrive.ToString(), homePath.ToString())

it fails because it produces: \\\\Users\\\\myusername\\\\myFolder它失败,因为它产生: \\\\Users\\\\myusername\\\\myFolder

I don't have a machine to test it on, but %HOMESHARE% might work for you.我没有机器来测试它,但%HOMESHARE%可能适合你。 Otherwise, here's a pretty good list of environment variables .否则,这里有一个很好的环境变量列表

Just for future reference, the list of pre-defined variables in Windows 10, taken from Windows 10 default environment variables .仅供将来参考,Windows 10 中的预定义变量列表取自Windows 10 默认环境变量

VARIABLE多变的 WINDOWS 10 WINDOWS 10
%ALLUSERSPROFILE% %ALLUSERSPROFILE% C:\ProgramData C:\程序数据
%APPDATA% %应用程序数据% C:\Users{username}\AppData\Roaming C:\Users{用户名}\AppData\Roaming
%CD% %光盘% Current directory full path.当前目录完整路径。
(cmd only) (仅限命令)
%CMDCMDLINE% %CMDCMDLINE% Returns exact command line used to start current cmd.exe session.返回用于启动当前 cmd.exe session 的确切命令行。
(cmd only) (仅限命令)
%CMDEXTVERSION% %CMDEXTVERSION% Number of current command processor extensions.当前命令处理器扩展的数量。
(cmd only) (仅限命令)
%CommonProgramFiles% %CommonProgramFiles% C:\Program Files\Common Files C:\Program Files\Common Files
%CommonProgramFiles(x86)% %CommonProgramFiles(x86)% C:\Program Files (x86)\Common Files C:\Program Files (x86)\Common Files
%CommonProgramW6432% %CommonProgramW6432% C:\Program Files\Common Files C:\Program Files\Common Files
%COMPUTERNAME% %COMPUTERNAME% The computer name of the current local system.当前本地系统的计算机名称。
%COMSPEC% %COMSPEC% C:\Windows\System32\cmd.exe C:\Windows\System32\cmd.exe
%DATE% %日期% Current date in format determined by Date command.当前日期的格式由 Date 命令确定。
(cmd only) (仅限命令)
%ERRORLEVEL% %错误级别% Number defining exit status of previous command or program.定义上一个命令或程序退出状态的数字。
(cmd only) (仅限命令)
%HOMEDRIVE% %HOMEDRIVE% C:| C:|
%HOMEPATH% %HOMEPATH% C:\Users{username} C:\用户{用户名}
%LOCALAPPDATA% %本地应用数据% C:\Users{username}\AppData\Local C:\Users{用户名}\AppData\Local
%LOGONSERVER% %登录服务器% \{domain_logon_server} \{domain_logon_server}
\MicrosoftAccount \微软帐户
%NUMBER_OF_PROCESSORS% %NUMBER_OF_PROCESSORS% 8 8个
%OS% %OS% Windows_NT Windows_NT
%PATH% %小路% C:\Windows; C:\Windows;
C:\Windows\System32; C:\Windows\System32;
C:\Windows\System32\Wbem; C:\Windows\System32\Wbem;
C:\Windows\System32\WindowsPowerShell\v1.0 C:\Windows\System32\WindowsPowerShell\v1.0
%PathExt% %路径扩展% .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
%PROCESSOR_ARCHITECTURE% %PROCESSOR_ARCHITECTURE% AMD64 AMD64
%PROCESSOR_IDENTIFIER% %PROCESSOR_IDENTIFIER% Intel64 Family 6 Model 158 Stepping 9, GenuineIntel Intel64 家族 6 Model 158 步进 9,GenuineIntel
%PROCESSOR_LEVEL% %PROCESSOR_LEVEL% 6 6个
%PROCESSOR_REVISION% %PROCESSOR_REVISION% 9e09 9e09
%PROGRAMDATA% %程序数据% C:\ProgramData C:\程序数据
%PROGRAMFILES% %程序文件% C:\Program Files C:\程序文件
%ProgramW6432% %程序W6432% C:\Program Files C:\程序文件
%PROGRAMFILES(X86)% %PROGRAMFILES(X86)% C:\Program Files (x86) C:\程序文件 (x86)
%PROMPT% %迅速的% Code for current command prompt format.当前命令提示符格式的代码。
Code is usually $P$G代码通常是 $P$G
(cmd only) (仅限命令)
%PSModulePath% %PSModulePath% C:\Windows\system32\WindowsPowerShell\v1.0\Modules| C:\Windows\system32\WindowsPowerShell\v1.0\Modules|
%PUBLIC% %民众% C:\Users\Public C:\用户\公共
%RANDOM% %随机的% To get random number between 0 and 32767.获取 0 到 32767 之间的随机数。
(cmd only) (仅限命令)
%SessionName% %SessionName% When logging on directly to machine, returns "Console".当直接登录到机器时,返回“Console”。
When client connects via terminal server session, is combination当客户端通过终端服务器 session 连接时,是组合
of connection name, followed by pound symbol {#} and session number.连接名称,后跟井号 {#} 和 session 编号。
%SystemDrive% %SystemDrive% C: C:
%SystemRoot% %SystemRoot% C:\Windows C:\Windows
%TEMP% %温度% C:\Users{username}\AppData\Local\Temp C:\Users{用户名}\AppData\Local\Temp
%TMP% %TMP% C:\Users{username}\AppData\Local\Temp C:\Users{用户名}\AppData\Local\Temp
%TIME% %时间% Current time in format determined by Time command.当前时间的格式由 Time 命令确定。
(cmd only) (仅限命令)
%USERDOMAIN% %用户域% The.network domain name associated with the current user.与当前用户关联的.network 域名。
%USERDOMAIN_ROAMINGPROFILE% %USERDOMAIN_ROAMINGPROFILE% The.network domain name associated with the current roaming profile.与当前漫游配置文件关联的.network 域名。
%USERNAME% %用户名% {username} {用户名}
%USERPROFILE% %用户资料% C:\Users{username} C:\用户{用户名}
%WINDIR% %风向% C:\Windows C:\Windows

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM