user1589780
user1589780

Reputation: 73

Absolute path required?

Usually when I build an application in C# which can digest command line parameters, if these parameters are file paths strings, I could choose to use relative paths as well as absolute paths to refer to a specific file on my computer and use it in the program.

In my last project, my application does not work if I give it a relative path from the command prompt. But in debug mode in VS 2010, it digests relative paths. From the command prompt it requires an absolute path to work.

Upvotes: 3

Views: 9612

Answers (2)

Michael G
Michael G

Reputation: 6745

You need to set the working directory. See: Directory.SetCurrentDirectory Method

Example:

System.IO.Directory.SetCurrentDirectory( System.AppDomain.CurrentDomain.BaseDirectory );

In a debug build the Current Directory is set to debug\bin by default.

Specifies the working directory of the program being debugged. In Visual C#, the working directory is the directory the application is launched from \bin\debug by default.

http://msdn.microsoft.com/en-us/library/2kf0yb05.aspx

You can also retrieve the assembly's path using Assembly.GetEntryAssembly() or Assembly.GetExecutingAssembly() and then using either the Location property or the CodeBase property.

Upvotes: 4

huysentruitw
huysentruitw

Reputation: 28141

You can turn the relative path into an absolute paths yourself, like this:

if (!Path.IsPathRooted(path))
    path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + path;

Or change the current directory to the executable path:

string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Directory.SetCurrentDirectory(exePath);

Upvotes: 2

Related Questions