Reputation: 599
I want to make a directory within the %appdata% folder. This is what I have so far:
public MainForm() {
Directory.CreateDirectory(@"%appdata%\ExampleDirectory");
}
This does not work, but it also doesn't crash or show any errors of any kind. How would I go about doing this? I have done research, and it does work if I use the actual path:
Directory.CreateDirectory(@"C:\Users\username\AppData\Roaming\ExampleDirectory");
However, it does not work when I use the %appdata%. This is problematic as I don't know the usernames of the people using the program, so I can't use the full path.
I have also tried this:
var appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var Example = Path.Combine(appdata, @"\Example");
Directory.CreateDirectory(Example);
And it also does not work
Upvotes: 2
Views: 3555
Reputation: 21
Try:
string example = Environment.ExpandEnvironmentVariables(@"%AppData%\Example");
Directory.CreateDirectory(example);
Environment.ExpandEnvironmentVariables()
will replace the environment variable AppData
with its value, usually C:\Users\<Username>\Appdata\Roaming
.
To get a list of your environment variables, run the set
command with no arguments from the command line.
Upvotes: 2
Reputation: 43936
You can use Environment.GetFolderPath()
and Environment.SpecialFolder.ApplicationData
:
string appDatafolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
string folder = Path.Combine(appDatafolder, "ExampleDirectory");
Directory.CreateDirectory(folder);
This will create the folder under C:\Users\<userName>\AppData\Roaming
.
Using SpecialFolder.LocalApplicationData
will use AppData\Local
instead.
To get AppData
only use:
string appDatafolder = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)));
See Environment.SpecialFolder
and Environment.GetFolderPath()
on MSDN for more information
Upvotes: 0
Reputation: 958
Something like this?
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var path = Path.Combine(appData, @"\ExampleDirectory");
Directory.CreateDirectory(path);
Upvotes: 0
Reputation: 1071
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);
Upvotes: 3