Question

My code access a file which is in "Conf" directory inside my project directory. I am currently 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

Was it helpful?

Solution

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

OTHER TIPS

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...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top