Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get/set a winforms application's working directory?

Tags:

c#

winforms

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?

like image 849
Mike Avatar asked Dec 03 '25 00:12

Mike


2 Answers

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

like image 190
BobbyShaftoe Avatar answered Dec 05 '25 15:12

BobbyShaftoe


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)
like image 32
Fredrik Mörk Avatar answered Dec 05 '25 14:12

Fredrik Mörk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!