如何正确设置localappdata路径,而不是显示完整路径(Path.Combine& Environment.GetFolderPath)

时间:2016-08-27 10:15:39

标签: c# visual-studio

我尝试使用Path.Combine,但是突出显示了字符串(appdatapath),帮助者说#34;字段初始化程序无法引用非静态字段,方法或属性&#39 ; MySuperAPP.appdatapath' "

代码是:

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

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

我想要的是: string path =" C:/ Users / USER / AppData / Local / Some / Dir /"

我尝试了什么:

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;

我认为我试过的变种可能是错的......) 需要你的建议)谢谢!)

1 个答案:

答案 0 :(得分:0)

当您initialize字段时(这意味着:当您提供值为runtime的动态字段时),它必须是static值。 因此,您必须声明" appdatapath"为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()
    {
        InitializeComponent();
    }
}

还要确保您的声明顺序正确:

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

最终:如果你有更多的目录要合并,请将每个部分分开放置:

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