我的代码访问一个文件,该文件位于项目目录下的"Conf“目录中。我目前正在使用如下所示的绝对路径打开文件:
File.ReadAllLines("C:\project name\Conf\filename");我在想,是否可以使用如下的相对路径
File.ReadAllLines("/Conf/filename");但是它不工作;正如预期的那样,它抛出了异常。我检查了MSDN (链接如下),但似乎"ReadAllLines()“方法不接受相对路径。
http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx
有什么想法吗?如何使用相对路径而不是绝对路径?
谢谢,Rahul
发布于 2014-01-25 13:14:54
这是我最喜欢的方式。
/此类必须与嵌入资源位于同一文件夹中/公有类GetResources {私有静态只读类型_type = typeof(GetResources);公共静态字符串Get(string fileName) { using (var stream = _type.Assembly.GetManifestResourceStream (_type.Namespace + ".“+ fileName)) { if (stream != null) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd();}}抛出新的FileNotFoundException(fileName);} }
发布于 2011-06-23 20:32:23
如MSDN中所述,您不能使用相对路径,但是可以使用Environment.CurrentDirectory或System.Reflection.Assembly.GetExecutingAssembly().Location。
发布于 2015-12-10 21:30:03
为了让事情变得简单,使用以下命令:
string current_path = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string[] lines_from_file = System.IO.File.ReadAllLines(current_path + "/Conf/filename");
...additional black magic here...https://stackoverflow.com/questions/5315072
复制相似问题