3

To get the Application's root I am Currently using:

Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6)

But that feels sloppy to me. Is there a better way to get the root directory of the application and set that to the working directory?

2 Answers 2

8

So, you can change directory by just using Environment.CurrentDirectory = (sum directory). There are many ways to get the original executing directory, one way is essentially the way you described and another is through Directory.GetCurrentDirectory() if you have not changed the directory.

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Get the current directory.
            string path = Directory.GetCurrentDirectory();
            string target = @"c:\temp";
            Console.WriteLine("The current directory is {0}", path);
            if (!Directory.Exists(target)) 
            {
                Directory.CreateDirectory(target);
            }

            // Change the current directory.
            Environment.CurrentDirectory = (target);
            if (path.Equals(Directory.GetCurrentDirectory())) 
            {
                Console.WriteLine("You are in the temp directory.");
            } 
            else 
            {
                Console.WriteLine("You are not in the temp directory.");
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }

ref

5

What is it that you want; the working directory, or the directory in which the assembly is located?

For the current directory, you can use Environment.CurrentDirectory. For the directory in which the assembly is located, you can use this:

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

Not the answer you're looking for? Browse other questions tagged or ask your own question.