2016-08-12 71 views
-5

这里使用VS 2015年社区和C#我试图读取存储在该项目名为lib文件夹内一个JSON文件lib/user.jsonC#目录未发现异常

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

但我正在逐渐目录未发现异常

enter image description here

您能否让我知道为什么会发生这种情况?由于

+1

我猜这是因为该文件不存在。至少不是程序期望的地方。你确认它确实吗?什么是您期望程序找到的文件的绝对路径? – itsme86

+0

我认为你已经检查过路径是否存在了吗? – Steve

+1

您是否已确认将'/ lib/user.json'文件作为'bin/Debug'文件夹(或'bin/Release',或任何启动该应用程序的文件夹)的子文件,因为这是应用程序将搜索它,而不是在项目的文件夹中。 –

回答

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' 
+5

这是一个好主意,但我主张'Path.Combine()':'return Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly()。Location),filename);' – itsme86