17

How do I programmically get the File Path of a File In my project?

 string fileContent = File.ReadAllText(LocalConstants.EMAIL_PATH);

The EMAIL_PATH I added to my project as a text file. This line of code throws an exception because by default it is looking in the system32 folder for some reason. I need to set it to the projects directory.

Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152

3 Answers3

30

You could use Path.Combine and AppDomain.CurrentDomain.BaseDirectory:

string fileName = "SampleFile.txt";
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LocalConstants.EMAIL_PATH, fileName);

Returns in a test project in debug mode this path(when LocalConstants.EMAIL_PATH="Emails"):

C:\****\****\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsFormsApplication1\bin\Debug\Emails\SampleFile.txt
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You can use Environment.CurrentDirectory

See: http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx

For further reading.

edit*

string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

Will do the same and is perhaps a little safer.

dtsg
  • 4,408
  • 4
  • 30
  • 40
  • It will point to where ever your working directory is. I just ran a demo on a test console app and the output was: "c:\users\duane\documents\visual studio 2010\Projects\EnvironmentDemo\EnvironmentDemo\bin\Debug", could you post the string you get from this property? – dtsg May 22 '12 at 15:07
  • 1
    The current directory isn't always the directory of your application. If it's a support file then it's not safe to assume this. – Adriano Repetti May 22 '12 at 15:14
  • Incorrect! This is the current working directory, not the directory your project is being served from. – Meekohi Apr 14 '21 at 19:48
0

This worked for me System.AppDomain.CurrentDomain.BaseDirectory.ToString()

Kapil
  • 191
  • 2
  • 5