【问题标题】:Relative path on File.ReadAllLines methodFile.ReadAllLines 方法的相对路径
【发布时间】:2011-07-15 23:07:55
【问题描述】:
我的代码访问了我的项目目录内的“Conf”目录中的一个文件。我目前正在使用如下绝对路径打开文件:
File.ReadAllLines("C:\project name\Conf\filename");
我在想是否可以使用像这样的相对路径
File.ReadAllLines("/Conf/filename");
但它不起作用;正如预期的那样,它抛出异常。我确实检查了 MSDN(下面的链接),但似乎“ReadAllLines()”方法不接受相对路径。
http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx
任何想法,我怎样才能使用相对路径而不是使用绝对路径?
谢谢,
拉胡尔
【问题讨论】:
标签:
c#-2.0
file.readalllines
【解决方案1】:
如 MSDN 中所述,您不能使用相对路径,但是您可以使用 Environment.CurrentDirectory 或 System.Reflection.Assembly.GetExecutingAssembly().Location
【解决方案2】:
这是我最喜欢的做法。
-
使您的文件成为嵌入式资源。
/// <summary>
/// This class must be in the same folder as the embedded resource
/// </summary>
public class GetResources
{
private static readonly Type _type = typeof(GetResources);
public static string Get(string fileName)
{
using (var stream =
_type.Assembly.GetManifestResourceStream
(_type.Namespace + "." + fileName))
{
if (stream != null)
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
throw new FileNotFoundException(fileName);
}
}
【解决方案3】:
为简单起见,请使用以下内容:
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...