Ashley
Ashley

Reputation: 599

How to create a directory in %appdata%

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

Answers (4)

Pedro Caleiro
Pedro Caleiro

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

Ren&#233; Vogt
Ren&#233; Vogt

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

StackUseR
StackUseR

Reputation: 958

Something like this?

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

Upvotes: 0

Meyssam Toluie
Meyssam Toluie

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

Related Questions