wrepaest
wrepaest

Reputation: 71

C# create dir in %AppData%

I want create directory (if not exist) in path AppData/Roaming/test. But my code doesn't work, I dont know why. Can you help me?

        string path;
        path = @"%AppData%\Roaming\test\";
        path = Environment.ExpandEnvironmentVariables(path);
        Console.WriteLine(path);

        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

This code doen't create dir.

Upvotes: 6

Views: 4807

Answers (2)

Old Fox
Old Fox

Reputation: 8725

%AppData% is a SpecialFolder.

change your code from:

path = @"%AppData%\Roaming\test\";

to:

var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var path = Path.Combine(appDataPath, @"test\");
if (!Directory.Exists(path))
        Directory.CreateDirectory(path);

Upvotes: 11

Stewart_R
Stewart_R

Reputation: 14515

You should really use Environment.SpecialFolders to reach special folders rather than explicitly hard-coding a path.

Something like this would do the trick:

string path = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), "test");

if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}

Upvotes: 1

Related Questions