13

我在谷歌上找到了一些东西,但它不适用于 C# 控制台应用程序

我发现了什么:

string appPath = Path.GetDirectoryName(Application.ExecutablePath);

如何使用 c# Console Application 获取应用程序目录?

4

5 回答 5

14

应用程序不适用于控制台应用程序,它适用于 Windows 窗体。

要获取工作目录,您可以使用

Environment.CurrentDirectory

另外要获取可执行文件的目录,您可以使用:

AppDomain.CurrentDomain.BaseDirectory
于 2012-10-13T16:50:05.203 回答
10

如果您仍想在控制台应用程序中使用 Application.ExecutablePath,您需要:

  1. 添加对 System.Windows.Forms 命名空间的引用
  2. 将 System.Windows.Forms 添加到您的使用部分

    using System;
    using System.IO;
    using System.Windows.Forms;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string appDirectory = Path.GetDirectoryName(Application.ExecutablePath);
                Console.WriteLine(appDirectory);
            }
        }
    }
    

您也可以使用Directory.GetCurrentDirectory()代替,Path.GetDirectoryName(Application.ExecutablePath)因此您不需要对 System.Windows.Forms 的引用。

如果您既不想包含名称空间System.IO也不包含System.Windows.Forms名称空间,那么您应该遵循 Reimeus 的回答。

于 2012-10-13T17:19:43.230 回答
9

请注意,路径有几种方法和陷阱。

  • 你要找什么位置?工作目录、.EXE 目录、DLLs 目录?

  • 您是否想要在服务或控制台应用程序中也能工作的代码?

  • 如果目录的尾部斜杠不一致,您的代码会中断吗?

让我们看一些选项:

Application.ExecutablePath

需要添加引用并加载应用程序命名空间。

Directory.GetCurrentDirectory
Environment.CurrentDirectory

如果程序是通过快捷方式、注册表、任务管理器运行的,这些将给出“Start In”文件夹,该文件夹可能与 .EXE 位置不同。

AppDomain.CurrentDomain.BaseDirectory

取决于它的运行效果是否包含尾部斜杠。这可能会破坏事情,例如 GetDirectoryName() 认为没有斜杠是文件,并将删除最后一部分。

这些都是我的建议,适用于 Form 和 Console 应用程序:

var AssemblyPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
or
var AssemblyPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

在主程序中使用时,两者是相同的。如果在 DLL 中使用,第一个返回加载 DLL 的 .EXE 目录,第二个返回 DLLs 目录。

于 2014-04-05T14:13:16.697 回答
3

尝试Directory.GetCurrentDirectory

于 2012-10-13T16:04:46.563 回答
0

我知道这已经很长时间了,但Assembly.GetExecutingAssembly().CodeBase对我有用。你只需Application.ExecutablePath要用它替换。

当然你必须添加using System.Reflection;

我试过使用System.Windows.Forms,但它给了我一个例外

于 2020-04-09T08:53:31.267 回答