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

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

Directory = System.Environment.GetEnvironmentVariable("public")+"MyCompanyName" // etc. 

或者,还有更好的方法?

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

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

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

 System.Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) 

指向“C:\ Users \ Public \ Desktop”。

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

这似乎有点可疑,但应该有效:

 // 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; 

请注意,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 

你看过这个吗?

http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

指定用于检索系统特殊文件夹的目录路径的枚举常量。

 Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) 

如果您希望放置一个可供所有用户访问的特定于应用程序的数据的位置,请将其用作基础:

 Environment.GetFolderPath(SpecialFolder.CommonApplicationData) 

另外,请考虑使用Path.Combine组合元素以形成新路径:

 Path.Combine( Environment.GetFolderPath(SpecialFolder.CommonApplicationData), "MyCompanyName") 

您可以通过查看获得所有这些%通配符%文字

Windows的>开始 – >注册表编辑器 – >

HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ Shell文件夹

然后,你执行

 using System; string path2Downloads = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Downloads"); string path2Music = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Music"); 

……等等……并测试:

 using System.IO; string[] files = { "" }; if (Directory.Exists(path2Music)) { files = Directory.GetFiles(path2Music); }