string path = Environment.CurrentDirectory;此方法返回当前工作目录的绝对路径。2. 使用Directory.GetCurrentDirectory

c#怎么获取当前路径

来源:这里教程网 时间:2026-02-21 16:49:03 作者:

C# 获取当前路径

获取当前路径在开发中经常会有用到,C#提供了多种方法来实现这一目的。

1. 使用Environment.CurrentDirectory

<code class="csharp">string path = Environment.CurrentDirectory;</code>

此方法返回当前工作目录的绝对路径。

2. 使用Directory.GetCurrentDirectory

<code class="csharp">string path = Directory.GetCurrentDirectory();</code>

此方法与Environment.CurrentDirectory相同,返回当前工作目录的绝对路径。

3. 使用Assembly.GetExecutingAssembly().Location

<code class="csharp">string path = Assembly.GetExecutingAssembly().Location;</code>

此方法返回当前应用程序的可执行文件路径。

示例:

<code class="csharp">using System;
using System.IO;
namespace GetCurrentDirectory
{
    class Program
    {
        static void Main()
        {
            // 使用 Environment.CurrentDirectory
            string path1 = Environment.CurrentDirectory;
            // 使用 Directory.GetCurrentDirectory
            string path2 = Directory.GetCurrentDirectory();
            // 使用 Assembly.GetExecutingAssembly().Location
            string path3 = Assembly.GetExecutingAssembly().Location;
            Console.WriteLine("Current Directory:");
            Console.WriteLine($"\tPath 1: {path1}");
            Console.WriteLine($"\tPath 2: {path2}");
            Console.WriteLine($"\tPath 3: {path3}");
        }
    }
}</code>

相关推荐