Nithesh Narayanan
Nithesh Narayanan

Reputation: 11775

Directory path in C#

In my winform application i need a path like

"D:\NEWD\WIN_NEW\Sales\Report\Report2.rdlc"

But i have only "Sales\Report\Report2.rdlc" the thing is dat i can't predict this path D:\NEWD\WIN_NEW but when am using

Directory.GetCurrentDirectory() + "\\Sales\\Report\\Report2.rdlc";

the path includes my bin\debug directory. How can i get the desired path?

Upvotes: 1

Views: 2621

Answers (3)

Tigran
Tigran

Reputation: 62265

Hmm, I think this is more triccky question as it seems: Considering that now you have bin\Debug, on deploy that path disappears, so saying GetCurrentDirectory(), I would say its better to use Path.GetDirectoryName(Application.ExecutablePath), you will be retrieved your deploy path. And also one day you may need to change file structure of your deploy, so...

Just in your bin\Debug or bin\Release replicate your future deploy files/folders layout, so your app will work in DEBUG and in DEPLOY in a same way. Always if it's possible.

Hope this helps.

Upvotes: 2

Bob Vale
Bob Vale

Reputation: 18474

If you know that you are always going to be in bin\debug you could just do

 var path=System.IO.Path.GetFullPath(@"..\..\Sales\Report\Report2.rdlc");

Or you could do some detection

var path=@"Sales\Report\Report2.rdlc";
var currentDir=System.IO.Directory.GetCurrentDirectory();
if (currentDir.ToLower().EndsWith(@"\bin\debug") ||
    currentDir.ToLower().EndsWith(@"\bin\release")) {

  path=System.IO.Path.GetFullPath(@"..\..\" + path);
} else {
  path=System.IO.Path.GetFullPath(path);
}

Another form of detection would be to do the path strip only if you are debugging in which case DEBUG should be set so you could do...

var path=@"Sales\Report\Report2.rdlc";
#if DEBUG

path=@"..\..\"+path;

# end if
path=System.IO.Path.GetFullPath(path);

This last version has the advantage that all the extra detection is not compiled into your release code.

Upvotes: 4

MADMap
MADMap

Reputation: 3192

While youre debugging, the Path of the current directory (the path where the program is executed) will be in the .\bin\debug\ dir.

When you deploy the tool, you wont have this problem anymore.

It seems, you want to deploy the "Sales" directory with your tool: so maybe you should include this in your solution and select it to be copied to the output-directory (.\bin\debug) with your executable.

Upvotes: 8

Related Questions