我想在%appdata%文件夹中创建一个目录。这就是我目前所拥有的:
public MainForm() {
Directory.CreateDirectory(@"%appdata%ExampleDirectory");
}
这不起作用,但它也不会崩溃或显示任何类型的错误。我该怎么做?我做过研究,如果我使用实际路径,它确实有效:
Directory.CreateDirectory(@"C:UsersusernameAppDataRoamingExampleDirectory");
但是,当我使用%appdata%时,它不起作用。这是有问题的,因为我不知道使用该程序的人的用户名,所以我不能使用完整的路径。
我也试过这个:
var appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var Example = Path.Combine(appdata, @"Example");
Directory.CreateDirectory(Example);
而且它也不工作
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);
尝试:
string example = Environment.ExpandEnvironmentVariables(@"%AppData%Example");
Directory.CreateDirectory(example);
Environment.ExpandEnvironmentVariables()
会将环境变量AppData
替换为其值,通常为C:Users<Username>AppdataRoaming
。
要获得环境变量的列表,请在命令行中运行不带参数的set
命令。
类似的东西?
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var path = Path.Combine(appData, @"ExampleDirectory");
Directory.CreateDirectory(path);
您可以使用Environment.GetFolderPath()
和Environment.SpecialFolder.ApplicationData
:
string appDatafolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
string folder = Path.Combine(appDatafolder, "ExampleDirectory");
Directory.CreateDirectory(folder);
这将在C:Users<userName>AppDataRoaming
下创建文件夹。
使用SpecialFolder.LocalApplicationData
将使用AppDataLocal
。
仅使用获取AppData
string appDatafolder = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)));
有关更多信息,请参阅MSDN上的Environment.SpecialFolder
和Environment.GetFolderPath()