【问题标题】: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.CurrentDirectorySystem.Reflection.Assembly.GetExecutingAssembly().Location

    【讨论】:

      【解决方案2】:

      这是我最喜欢的做法。

      1. 使您的文件成为嵌入式资源。

            /// <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...
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-29
          • 2012-03-11
          • 1970-01-01
          • 2015-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-11
          相关资源
          最近更新 更多