我在谷歌上找到了一些东西,但它不适用于 C# 控制台应用程序
我发现了什么:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
如何使用 c# Console Application 获取应用程序目录?
应用程序不适用于控制台应用程序,它适用于 Windows 窗体。
要获取工作目录,您可以使用
Environment.CurrentDirectory
另外要获取可执行文件的目录,您可以使用:
AppDomain.CurrentDomain.BaseDirectory
如果您仍想在控制台应用程序中使用 Application.ExecutablePath,您需要:
将 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 的回答。
请注意,路径有几种方法和陷阱。
你要找什么位置?工作目录、.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 目录。
我知道这已经很长时间了,但Assembly.GetExecutingAssembly().CodeBase
对我有用。你只需Application.ExecutablePath
要用它替换。
当然你必须添加using System.Reflection;
我试过使用System.Windows.Forms
,但它给了我一个例外