如何在C#中以编程方式引用C:\ Users\Public目录

Jeb*_*Jeb 16 .net c# environment-variables

以编程方式引用公用文件夹是否安全:

Directory = System.Environment.GetEnvironmentVariable("public")+"MyCompanyName" // etc.
Run Code Online (Sandbox Code Playgroud)

或者,还有更好的方法?

再次,如果有人为公共删除环境变量,并且这对于不同的语言操作系统使用是否安全呢?

具体如下:如何从VS 2010部署安装项目安装到Windows 7中的Public目录

Dan*_*Tao 16

这似乎有点可疑,但它应该工作:

// This should give you something like C:\Users\Public\Documents
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);

var directory = new DirectoryInfo(documentsPath);

// Now this should give you something like C:\Users\Public
string commonPath = directory.Parent.FullName;
Run Code Online (Sandbox Code Playgroud)


小智 15

这取决于你想要达到的目标.有一个叫做的枚举SpecialFolder.您可以使用它来获取某些目录的路径.例如:

System.Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory)
Run Code Online (Sandbox Code Playgroud)

指向"C:\ Users\Public\Desktop".

恕我直言,你的方式没有错,但我会做一些异常处理,以防EnvVar真的丢失.您也可以将ENUM与"CommonDesktopDirectory"一起使用,并删除"\ Desktop"部分.

  • 不确定为什么这被标记为答案,甚至在错误时投票.CommonDesktopDirectory不是.Net 3.5的有效枚举,它是用于VS2008的,它是如何标记问题的. (2认同)

小智 6

请注意,Environment.SpecialFolder.CommonDesktopDirectory仅在.NET 4.0中可用.对于我的.NET 3.5系统(Windows 7或XP),我使用了Shell文件夹的注册表项.我的代码片段是在VB.NET中.

Private mRegShellPath="Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
Private mCommonDesktop = Nothing

' dgp rev 3/8/2012
Private ReadOnly Property CommonDesktop As String
    Get
        If mCommonDesktop Is Nothing Then
            Dim RegKey As RegistryKey
            Try
                RegKey = Registry.LocalMachine.OpenSubKey(mRegShellPath, False)
                mCommonDesktop = RegKey.GetValue("Common Desktop")
            Catch ex As Exception
                mCommonDesktop = ""
            End Try
        End If

        Return mCommonDesktop
    End Get

End Property
Run Code Online (Sandbox Code Playgroud)