0

For example if I would like to get number of files in the project's directory. In Java I would write:

int numberOfFiles = new File(".").listFiles().length;

But I do not know how to get path to the project's directory in .NET. How to achieve the same goal in C#?

Yoda
  • 17,363
  • 67
  • 204
  • 344
  • Possible duplicate: http://stackoverflow.com/questions/1658518/getting-the-absolute-path-of-the-executable-using-c – Pedrom Jan 08 '14 at 20:42

3 Answers3

2

It is simple

var path = Path.GetDirectoryName(Application.ExecutablePath);
var files = Directory.GetFiles(path);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

It's close - use:

int numberOfFiles = Directory.GetFiles(".").Length
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Is there any difference(in the result, effectivness) comparing to John Koerner solution? – Yoda Jan 08 '14 at 22:10
  • 1
    The _result_ should be the same. You'd have to try it both ways to see if the _performance_ is different. – D Stanley Jan 08 '14 at 22:11
  • Which one would you prefer? I would like to know reference solution -->purist's solution. – Yoda Jan 08 '14 at 22:15
  • 1
    Now that I think about it - the _current directory_ could be different that the _executable path_, so the results _could_ be different if for example, you started the app with a shortcut that set a different startup directory. – D Stanley Jan 08 '14 at 22:20
  • If I run app by a shortcut from desktop the `executable path` or `current directory` will lead to the "real" application directory? – Yoda Jan 08 '14 at 23:35
  • Yes, unless a different directory is set in the Startup Directory field - that _that_ will be the "current" directory. – D Stanley Jan 09 '14 at 14:02
1

You can get the path to the executable using Application.ExecutablePath and then get the directory from there. Once you have the directory, it is easy to get the file count:

var executingDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
var numFiles = System.IO.Directory.GetFiles(executingDir).Count();
Console.WriteLine(numFiles);
John Koerner
  • 37,428
  • 8
  • 84
  • 134