获得在C#中的主目录的路径? [英] Getting the path of the home directory in C#?

查看:290
本文介绍了获得在C#中的主目录的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,我已经检查Environment.SpecialFolder,但没有什么在那里这一点。

我想在C#中的当前用户的主目录。 (例如: C:\ Documents和Settings \用户在XP下, C:\用户\用户在Vista和 / home / user中 Unix下。)

我知道我可以读取环境变量来发现这一点,但我想这样做的一个跨平台的方式。

有什么办法,我可以用.NET(preferably使用的mscorlib)?

做到这一点

更新:好吧,这是code我最终使用:

 字符串HOMEPATH =(Environment.OSVersion.Platform == PlatformID.Unix ||
                   Environment.OSVersion.Platform == PlatformID.MacOSX)
    ? Environment.GetEnvironmentVariable(HOME)
    :Environment.ExpandEnvironmentVariables(%HOMEDRIVE %% HOMEPATH%);
 

解决方案

Environment.SpecialFolder.Personal实际上并不返回主文件夹,则返回的我的文档的文件夹中。得到主文件夹在Win32上最安全的方法是阅读%HOMEDRIVE %% HOMEPATH%。阅读环境变量其实是非常便携做到(在UNIX和Windows),所以我不知道为什么海报想的没有的做到这一点。

编辑补充:的对于跨平台(在Window / Linux)C#中,我读到的Windows在Unix和OSX和%HOMEDRIVE %% HOMEPATH%$ HOME

Okay, I've checked Environment.SpecialFolder, but there's nothing in there for this.

I want to get the home directory of the current user in C#. (e.g. c:\documents and settings\user under XP, c:\users\user under Vista, and /home/user under Unix.)

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)?

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%");

解决方案

Environment.SpecialFolder.Personal doesn't actually return the home folder, it returns the My Documents folder. The safest way to get the home folder on Win32 is to read %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.

Edited to add: For crossplatform (Windows/Unix) C#, I'd read $HOME on Unix and OSX and %HOMEDRIVE%%HOMEPATH% on Windows.

这篇关于获得在C#中的主目录的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆