Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Error creating directory in SpecialFolder.LocalApplicationData on Windows 7 as a non Admin

Tags:

c#

windows-7

I'm getting the error "Access to the path 'LocalApplicationData\MyProgram\' is denied." when trying to create a directory for my log file. This is when I'm running the program as a non-admin user.

Directory.CreateDirectory(System.Environment.SpecialFolder.LocalApplicationData + "\\MyProgram\\");

Why would this be?

Thanks

like image 585
Jade M Avatar asked Jan 02 '10 21:01

Jade M


People also ask

What is C in simple words?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C or C++ same?

While C and C++ may sound similar, their features and usage differ. C is a procedural programming language that support objects and classes. On the other hand C++ is an enhanced version of C programming with object-oriented programming support.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


2 Answers

LocalApplicationData is just an enum value. You will have to use it in combination with GetFolderPath:

string folder = Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.LocalApplicationData), 
    "MyProgram");
like image 135
Dirk Vollmar Avatar answered Oct 17 '22 10:10

Dirk Vollmar


You're trying to access the enumeration value LocalApplicationData as if it were a string. It's not. You need to find the folder path with GetFolderPath:

string path = Environment.GetFolderPath(
    System.Environment.SpecialFolder.LocalApplicationData);

Incidentally, it's better form, and less error-prone, to use Path.Combine to build up paths, rather than doing it by hand:

string path = Path.Combine(@"C:\", "dir"); // gives you "C:\dir"

...and so your code would end up looking like:

string appDataPath = Environment.GetFolderPath
    (System.Environment.SpecialFolder.LocalApplicationData);
string path = Path.Combine(appDataPath, "MyProgram");
Directory.CreateDirectory(path);
like image 12
Michael Petrotta Avatar answered Oct 17 '22 11:10

Michael Petrotta