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

另请参阅