2011-01-10 59 views
10

是否安全通過以編程方式引用公用文件夾:如何引用C:用戶編程Public目錄在C#

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

,或是否有更好的辦法?

再說一遍,如果某人刪除公開的環境變量,並且可以安全地用於不同的語言操作系統?

此如下:How to install to the Public directory in Windows 7 from the VS 2010 deployment Setup Project

+1

作爲邊注,我建議使用[Path.Combine](http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx)反對連接目錄。 – 2011-01-10 18:08:36

+0

你擔心與Windows XP的向後兼容性嗎? %public%環境變量似乎已在Vista中引入; WinXP有%allusersprofile%環境變量指向%systemdrive%\ Documents and Settings \ All Users,但%public%未定義。 – 48klocs 2011-01-10 18:12:35

+0

感謝您的信息;沒有,這純粹是Vista/7。 – Jeb 2011-01-11 09:33:19

回答

10

這取決於你想要達到的目標。 有一個名爲SpecialFolder的枚舉。您可以使用它來獲取某些目錄的路徑。 例如:

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

指向 「C:\用戶\公共\桌面」。

恕我直言,你的方式沒有錯,雖然我會做一些例外處理的情況下,EnvVar是真的失蹤。 您也可以將ENUM與「CommonDesktopDirectory」一起使用並擺脫「\ Desktop」部分。

9

這似乎是一點點懷疑,但它應該工作:

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

感謝您的信息。不幸的是,我的項目目標鎖定了.Net框架的3.5個版本,它不排除CommonDocuments枚舉成員(我們希望在舊軟件和與Windows 7兼容的新版本之間保持最低限度的變化)。 – Jeb 2011-01-11 09:43:49

3

如果你想放,可以被所有用戶訪問應用程序特定數據的地方,用作基地:

Environment.GetFolderPath(SpecialFolder.CommonApplicationData) 

此外,請考慮使用Path.Combine將元素組合到形成新路徑:

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

請注意,Environment.SpecialFolder.CommonDesktopDirectory僅在.NET 4.0中可用。對於我的.NET 3.5系統(Windows 7或XP),我使用Shell Folders的註冊表項。我的代碼片段在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 
1

您可以通過查看得到所有這些通配符%文字%到

Windows的>開始 - >註冊表編輯器 - >

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders

然後,您執行

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); 
}