[C#] How to Get and Change the Current Working Directory

To get the “Current Directory,” which is the base directory where the program is currently running, use the Directory.GetCurrentDirectory method. This directory serves as the starting point when reading or writing files using relative paths (e.g., ./data.txt).

目次

Implementation Sample: Checking and Changing the Workspace

The following code displays the directory at startup, moves the workspace to a subfolder using SetCurrentDirectory, and verifies that the resolution of relative paths changes.

Sample Code

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        // 1. Get the current working directory
        string startDir = Directory.GetCurrentDirectory();
        Console.WriteLine($"[Startup] {startDir}");

        // Name of the test subfolder
        string subDirName = "WorkArea";
        
        // Create the folder if it does not exist
        if (!Directory.Exists(subDirName))
        {
            Directory.CreateDirectory(subDirName);
        }

        // 2. Change the working directory
        // From here on, relative paths will be based on this subfolder
        Directory.SetCurrentDirectory(subDirName);

        // Verify the path after the change
        string newDir = Directory.GetCurrentDirectory();
        Console.WriteLine($"[After Moving] {newDir}");

        // 3. Test creating a file using a relative path
        // Creating a file with just a name (no path) puts it in the current directory
        string fileName = "test.log";
        File.WriteAllText(fileName, "Log content");

        // Check the absolute path to see where the file was actually created
        string fullPath = Path.GetFullPath(fileName);
        Console.WriteLine($"[Created File] {fullPath}");
    }
}

Execution Result (Example)

[Startup] C:\Projects\MyApp\bin\Debug\net6.0
[After Moving] C:\Projects\MyApp\bin\Debug\net6.0\WorkArea
[Created File] C:\Projects\MyApp\bin\Debug\net6.0\WorkArea\test.log

Explanation and Technical Points

1. Difference from the Executable File’s Location

It is important to note that Directory.GetCurrentDirectory() returns the “current working location,” which is not always the same as the folder where the EXE file is stored. For example, if you start the program from a shortcut or call the EXE from a different location in the command prompt, the current directory will be the location where the command was executed.

If you need to reliably get the location where the EXE file resides, use AppContext.BaseDirectory.

2. Directory.SetCurrentDirectory

This method changes the working directory while the program is running. Once called, operations like File.Open("file.txt", ...) will refer to the new location if no specific path is provided. While useful, this affects the entire program. Changing it carelessly can cause “file not found” errors in other parts of your process that rely on the previous directory structure.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次