找不到C#目录

时间:2016-08-12 17:20:43

标签: c#

这里使用VS 2015社区和C#我试图读取存储在项目中名为lib的文件夹中的JSON文件lib/user.json

 String jsonSTR = File.ReadAllText("lib/user.json");

但我收到了目录未找到的例外

enter image description here

你能告诉我为什么会这样吗?感谢

1 个答案:

答案 0 :(得分:3)

你应该使用反射来进入相对路径:

public static string PredictAbsoluteFilePath(string fileName)
{
    return Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), fileName);
}

你可以像这样使用它:

string path = Utils.PredictAbsoluteFilePath("relativeFile.xml");
//assuming that currect executing file is in D:\Programs\MyApp directory
//path is now 'D:\Programs\MyApp\relativeFile.xml'