Directory.GetCurrentDirectory 方法

定義

取得應用程式的目前工作目錄。

public static string GetCurrentDirectory ();

傳回

字串,其中包含目前工作目錄的絕對路徑,且結尾不會以反斜杠 (\) 結尾。

例外狀況

呼叫端沒有必要的權限。

作業系統是 Windows CE,它沒有當前的目錄功能。

.NET Compact Framework 提供方法,但目前不支援。

範例

下列範例示範如何使用 GetCurrentDirectory 方法。

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());
        }
    }
}

備註

目前的目錄與原始目錄不同,這是程序啟動的來源目錄。

如需一般 I/O 工作的清單,請參閱 一般 I/O 工作

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另請參閱