5

I know that in the same directory where my code is being executed some files are located. I need to find them and pass to another method:

MyLib.dll
Target1.dll
Target2.dll

Foo(new[] { "..\\..\\Target1.dll", "..\\..\\Target2.dll" });

So I call System.IO.Directory.GetFiles(path, "*.dll"). But now I need to get know the path:

string path = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName)

but is there more short way?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • [This post](http://stackoverflow.com/questions/3163495/better-way-to-get-the-base-directory) should give you a few options – mhenrixon Jul 17 '10 at 11:47

2 Answers2

6

You may try the Environment.CurrentDirectory property. Note that depending on the type of application (Console, WinForms, ASP.NET, Windows Service, ...) and the way it is run this might behave differently.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I'm running NUnit test. In real world I call `Foo(Server.MapPath("~/bin"))` but in test I just want to scan the root directory of the assembly containing the test – abatishchev Jul 17 '10 at 11:48
  • Thanks! `Environment.CurrentDirectory` is what I was looking for. My call returns something from Temp but your - exactly what I need. – abatishchev Jul 17 '10 at 12:01
  • 1
    Environment.CurrentDirectory does not work as intended at all times. If your application accesses the standard Windows File Open Dialog box and you select some path there, then next call to Environment.CurrentDirectory will return that last selected path in the file open dialog instead of the path to the executing program. – 10100111001 Apr 30 '14 at 07:42
2

Environment.CurrentDirectory returns the current directory, not the directory where the executed code is located. If you use Directory.SetCurrentDirectory, or if you start the program using a shortcut where the directory is set this won't be the directory you are looking for.

Stick to your original solution. Hide the implementation (and make it shorter) using a property:

private DirectoryInfo ExecutingFolder
{
    get
    {
        return new DirectoryInfo (
            System.IO.Path.GetDirectoryName (
                System.Reflection.Assembly.GetExecutingAssembly().Location));
    }
}
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116