当前位置:首页C# > 正文

C#中如何获取当前目录和上级目录

作者:野牛程序员:2024-07-02 10:36:43C#阅读 2208
C#中如何获取当前目录和上级目录

C#中如何获取当前目录和上级目录:

在C#中,可以使用System.IO命名空间中的类和方法来获取当前目录和上级目录。以下是相关代码示例:

获取当前目录

可以使用Directory.GetCurrentDirectory()方法来获取当前工作目录:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 获取当前目录
        string currentDirectory = Directory.GetCurrentDirectory();
        Console.WriteLine("当前目录: " + currentDirectory);
    }
}

获取上级目录

可以通过获取当前目录,然后使用DirectoryInfo类的Parent属性来获取上级目录:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // 获取当前目录
        string currentDirectory = Directory.GetCurrentDirectory();
        // 获取上级目录
        DirectoryInfo parentDirectory = Directory.GetParent(currentDirectory);

        if (parentDirectory != null)
        {
            Console.WriteLine("上级目录: " + parentDirectory.FullName);
        }
        else
        {
            Console.WriteLine("上级目录不存在");
        }
    }
}

以上代码分别展示了如何获取当前目录和上级目录,输出结果会显示对应的路径。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
  • C#
  • 最新推荐

    热门点击