2016-05-18 107 views
2

我想在%appdata%文件夾中創建一個目錄。這是我到目前爲止:如何在%appdata%中創建目錄%

public MainForm() { 
    Directory.CreateDirectory(@"%appdata%\ExampleDirectory"); 
} 

這不起作用,但它也不會崩潰或顯示任何類型的錯誤。我會如何去做這件事?我曾經做過研究,如果我用實際路徑它的工作:

Directory.CreateDirectory(@"C:\Users\username\AppData\Roaming\ExampleDirectory"); 

然而,當我使用%APPDATA%這是行不通的。這是有問題的,因爲我不知道使用該程序的人的用戶名,所以我不能使用完整路徑。

我也試過這樣:

var appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); 
var Example = Path.Combine(appdata, @"\Example"); 
Directory.CreateDirectory(Example); 

而且它也不起作用

+1

的可能的複製[如何創建與C#應用程序數據文件夾(http://stackoverflow.com/questions/16500080/how-to-create-appdata-folder-with-c-sharp) – djthoms

回答

4
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); 

// Combine the base folder with your specific folder.... 
string specificFolder = Path.Combine(folder, "YourSpecificFolder"); 

// Check if folder exists and if not, create it 
if(!Directory.Exists(specificFolder)) 
    Directory.CreateDirectory(specificFolder); 
0

您可以使用Environment.GetFolderPath()Environment.SpecialFolder.ApplicationData

string appDatafolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); 
string folder = Path.Combine(appDatafolder, "ExampleDirectory"); 
Directory.CreateDirectory(folder); 

這將創建一個文件夾下C:\Users\<userName>\AppData\Roaming。使用SpecialFolder.LocalApplicationData將使用AppData\Local代替。

要獲得AppData只使用:

string appDatafolder = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))); 

有關更多信息,請參見Environment.SpecialFolderEnvironment.GetFolderPath() MSDN上

1

像這樣的事情?

var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); 
var path = Path.Combine(appData, @"\ExampleDirectory"); 
Directory.CreateDirectory(path); 
+0

是,這是訣竅。謝謝 – Towja

+0

提到不是。:-) –

+0

我剛試過這個,它不起作用 – Towja