0

So far I haven't found anything that would allow my program to access text files that are in the same folder as it. for example: if my file is in C:/testingfolder i would need to use C:/testingfolder/filenames.txt to access the other files, the problem with this is sometimes it wont be in c:/testingfolder but instead it might be in E:/importantfiles or F:/backup and it needs to run from all of those.

If anyone could explain or give code that showed how to make a longer path into a "same folder" path that would answer my question.

  • 3
    If you mean relative to the location of the process .exe [see here](http://stackoverflow.com/q/52797/314291). – StuartLC Dec 28 '14 at 18:26

2 Answers2

0

With the Environment.CurrentDirectory you can get the path of your process that is executing, then you should use System.IO.Path.Combine() method to concatenate this path with the name of your file, and you will get the absolute location of your file.

msporek
  • 1,187
  • 8
  • 21
  • It might be dangerous to use this method, see: [What is the difference between these ways of getting current directory?](http://stackoverflow.com/questions/18727692/what-is-the-difference-between-these-ways-of-getting-current-directory) – t3chb0t Dec 28 '14 at 18:41
0

You need to use System.IO and System.Text

using System;
using System.IO;
using System.Text;

then

static void Main(string[] args)
{
    string line = "";
    // look for the file "myfile.txt" in application root directory
    using (StreamReader sr = new StreamReader("myfile.txt"))
    {
        while ((line = sr.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }

    Console.ReadKey();
}
SUMIT
  • 38
  • 7