How to get / set the working directory of the winforms application?

To get the root of the application, I now use:

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

But it seems sloppy to me. Is there a better way to get the root directory of an application and install it in a working directory?

+3
source share
2 answers

So you can change the directory simply by using Envrionment.CurrentDirectory = (sum directory). There are many ways to get the original directoy executable, one of which is essentially described by you, and the other 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

+6
source

What you need; working directory or directory where the assembly is located?

Environment.CurrentDirectory. , , :

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

Source: https://habr.com/ru/post/1720488/


All Articles