开发者

Relative path on File.ReadAllLines method

开发者 https://www.devze.com 2023-02-16 19:54 出处:网络
My code access a file which is in \"Conf\" directory inside my project directory. I am curr开发者_开发百科ently opening the file using absolute path like below:

My code access a file which is in "Conf" directory inside my project directory. I am curr开发者_开发百科ently opening the file using absolute path like below:

File.ReadAllLines("C:\project name\Conf\filename");

I was thinikng if it's possible to use the relative path like

File.ReadAllLines("/Conf/filename");

But it's not working; as expected it throws exception. I did checked MSDN (link below) but seems "ReadAllLines()" methods doesn't accept relative path.

http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx

Any idea, how can I use the relative path instead using absolute path?

Thanks, Rahul


This is my favorite way of doing it.

  1. Make your file an embedded resource.

        /// <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);
        }
     }
    


As stated in MSDN you cannot use a relative path, however you might be able to use either Environment.CurrentDirectory or System.Reflection.Assembly.GetExecutingAssembly().Location


To make things simple, use the following:

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

精彩评论

暂无评论...
验证码 换一张
取 消