Search code examples
c#consoledirectorypublishappdata

How do i get right the directory of my application?


I've made a small console application (first publish in c#). but i cant use my resource files. I used textfiles can give it. It worked when i used the debug directory

My goal is to create a directory like this: Applicationmap + application.exe + setup resource map + configurations.txt Logger + .

Now if i try to reach the configuration file it sends me to: C:\Users\<username> \AppData\Local\Apps\2.0\D01L7N51.9EW\R7HB7NAB.B7Y \sele..tion_0000000000000000_0001.0000_92af5262ce6f49d8

While i'm expecting C:/Users/<username>/ Documents/<application>/ + resources/config.txt.

I've tried

string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Console.WriteLine(dir);

&&

Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));

&&

Console.WriteLine(Directory.GetCurrentDirectory());

but i always end up at the appdata map.


Solution

  • You could simply use Application.StartupPath (reference), but the outcome will always depend on where you place/install the executable file

    If you always want to point the current user's Documents folder (which is registered as a special folder within the operating system), like in your example, you could either use:

    String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    

    or (but at your own risk since its much less safe):

    String path = Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents");
    

    Once you have retrieved the correct Documents folder path with either the first or the second approach, combine it with the last part:

    path = Path.Combine(path, "resources/config.txt");
    

    For more information concerning the two approaches: