James
James

Reputation: 1945

get file path from current project

In my Visual Studio console application my project is located in the below location:

c:\MyProject\FilesToUpload\test.txt

I am trying to access this file using the following code:

string path = Path.Combine(Environment.CurrentDirectory, @"FilesToUpload\", "test.txt");

But this path returns: c:\MyProject\bin\debug\net461\FilesToUpload\test.txt

The path I would like to get is: c:\MyProject\FilesToUpload\test.txt

Upvotes: 3

Views: 3333

Answers (2)

Kjartan
Kjartan

Reputation: 19151

Environment.CurrentDirectory will return the path from which your program is currently running. What you will need to do is decide on one of the following:

  • A relation between that path and the directory "FilesToUpload".
  • A hard-coded path, such as c:\MyProject\FilesToUpload\
  • A configurable path, which you can then specify and read in your application. Personally, I'd prefer this option, as it will not be as dependent on where you run the application from.

In the first case, you could use something like this:

var relation = @"..\..\..\FilesToUpload\";
var currPath = Path.Combine(Environment.CurrentDirectory, relation, "test.txt");

Update / clarification:

For the first option, in your case (your example), using a relative path should effectively change your returned path from:

c:\MyProject\bin\debug\net461\FilesToUpload\test.txt

To:

c:\MyProject\bin\debug\net461\..\..\..\FilesToUpload\test.txt

Try this, and see how if it works - If the path is not exactly correct, you should be able to figure out how to adjust it.

Upvotes: 3

Sergey Vishnevskiy
Sergey Vishnevskiy

Reputation: 453

"Environment.CurrentDirectory" return correct path. Your application is an "exe" file but not source files. And it runs from a compile output directory. You don't need to get file from the "c:\MyProject\FilesToUpload\test.txt" but you to need change "Copy to Output Directory" property of the "test.txt" to "Copy Always". File properties

Upvotes: 1

Related Questions