Mr.Who Mr.Who - 11 months ago 53
C# Question

How to set localappdata path properly, not showing the full path(Path.Combine & Environment.GetFolderPath)

I'm trying to Path.Combine, but having highlighted string(appdatapath), helper say's that "a field initializer cannot reference the non-static field, method, or property'MySuperAPP.appdatapath' "

the code is :

string appdatapath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

string path = Path.Combine(appdatapath, "second/part/of/folderpath");

what i want is:
string path = "C:/Users/USER/AppData/Local/Some/Dir/"

what i tried :

string static appdatapath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

string static path = Path.Combine(appdatapath,"second/part/of/folderpath").ToString;


public static string GetMyLocalAppDir()
return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).ToString();
string path = Path.Combine(GetMyLocalAppDir(),"second/part/of/folderpath").ToString;

i think the variants that i'm tried may be wrong..)
need your advice) thank's!)

Answer Source

When you initialize a field (this mean: when you provide a dynamic field with a value at runtime) it must be a static value. Therefore you must declare "appdatapath" as static.

public partial class MainWindow : Window
    private static string appdatapath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

    private (static) string path = System.IO.Path.Combine(appdatapath, "second/part/of/folderpath"); //make this static if you want that this field can't be changed.
    public MainWindow()

Also make sure your declaration is in the right order:

public or private static or not type e.g. string name of variable

Finaly: if you have more directory's to combine, put eacht part separately:

Path.Combine(appdatapath, "second", "part", "of", "folderpath")