18

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.

4
  • Do you need the application directory? Commented May 22, 2012 at 14:50
  • I add a text file to my project. I need that directory Commented May 22, 2012 at 14:50
  • The projects root directory is what I need Commented May 22, 2012 at 14:51
  • Are you trying to embed a txt file into your executable? Commented May 22, 2012 at 14:59

3 Answers 3

32

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
Sign up to request clarification or add additional context in comments.

3 Comments

This code points to the bin/Debug folder. EMAIL_PATH is in the root folder of the project
Maybe my problem is I have to set the text files to copy to output. Is that the standard thing to do?
@NickLaMarca: You're refering to stackoverflow.com/a/857473/284240 ? Maybe, depends on your exact requirement.
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.

3 Comments

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?
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.
Incorrect! This is the current working directory, not the directory your project is being served from.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.