Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command line current working directory in a console app [duplicate]

Possible Duplicate:
How do I find out what directory my console app is running in with C#?

How to get current working directory of a console that runs a program so I could resolve relative paths passed as program args?

Lets say I've put my program here: c:\tools\program.exe But I'm invoking it from various places. Lets say I'm here: C:\Users\Me\Documents\ and I run this command program.exe --src=somefile.txt --dest=subdir\otherfile.txt

Environment.CurrentDirectory and System.Reflection.Assembly.GetExecutingAssembly().Location will return c:\tools but I would like to be able to resolve somefile.txt and subdir\oterfile.txt paths that are relative to C:\Users\Me\Documents\.

====== UPDATE ======

Thank you for your help. It seems that Environment.CurrentDirectory works as expected. It turned out that in my case the problem was caused by Xenocode's Postbuild tool (now called Spoon Virtual Application Studio) that I occasionally use to "pack" all program's files (including dlls, config, etc.) into one executable. It's very handy, but in this case the "virtualization" feature messed up my program's Environment variables. I've managed to solve that issue.

like image 700
SiliconMind Avatar asked Nov 27 '12 15:11

SiliconMind


2 Answers

Environment.CurrentDirectory gives you the Current Working Directory

Let me show a simple example:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Startup: " + Environment.CurrentDirectory);
        Environment.CurrentDirectory = @"D:\temp";
        Console.WriteLine("After:" + Environment.CurrentDirectory);
    }
}

Now I create two folders named D:\temp and D:\temp2
I put the executable in D:\temp
Open a command prompt and set the current working directory with cd D:\temp2
From that directory I run ..\temp\mytestapp.exe

the output is

Startup: D:\temp2
After: D:\temp

As a curiosity:

this was the documentation for Environment.CurrentDirectory in Net 1.1

Gets and sets the fully qualified path of the current directory; that is, the directory from which this process starts.

and this is the documentation in NET 4.0

Gets or sets the fully qualified path of the current working directory.

like image 169
Steve Avatar answered Nov 15 '22 14:11

Steve


Use the Environment and Path classes. http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx

var fqn = Path.Combine(Environment.CurrentDirectory, "somefile.txt")

But to play with your documents you need:

var fqn = Path.Combine(
     Environment.GetFolderPath(Environment.SpecialFolder.Person),
     "somefile.txt");

`fqn' is TLA for fully qualified name

like image 31
Richard Schneider Avatar answered Nov 15 '22 15:11

Richard Schneider