a12*_*773 13 c# directory console
我在谷歌上找到了一些东西,但它不适用于C#控制台应用程序
我找到了什么:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
Run Code Online (Sandbox Code Playgroud)
如何使用c#控制台应用程序获取应用程序目录?
Rei*_*eus 13
应用程序不适用于控制台应用程序,它适用于Windows窗体.
要获取工作目录,您可以使用
Environment.CurrentDirectory
Run Code Online (Sandbox Code Playgroud)
另外,要获取可执行文件的目录,您可以使用:
AppDomain.CurrentDomain.BaseDirectory
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 10
如果您仍想在控制台应用程序中使用Application.ExecutablePath,则需要:
将System.Windows.Forms添加到您的usings部分
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)您也可以使用Directory.GetCurrentDirectory()而不是,Path.GetDirectoryName(Application.ExecutablePath)因此您不需要对System.Windows.Forms的引用.
如果您不想既不包含名称空间System.IO也不包含System.Windows.Forms名称空间,那么您应该遵循Reimeus的答案.
请注意,路径有几种方法和PITFALLS.
你在哪个位置?工作目录,.EXE目录,DLLs目录?
您是否希望代码也适用于服务或控制台应用程序?
如果目录具有不一致的尾部斜杠,您的代码是否会中断?
让我们看看一些选项:
Application.ExecutablePath
Run Code Online (Sandbox Code Playgroud)
需要添加引用并加载Application命名空间.
Directory.GetCurrentDirectory
Environment.CurrentDirectory
Run Code Online (Sandbox Code Playgroud)
如果程序是由快捷方式,注册表,任务管理器运行,这将给"启动"文件夹中,这可以从该.exe位置不同.
AppDomain.CurrentDomain.BaseDirectory
Run Code Online (Sandbox Code Playgroud)
取决于它的运行方式是否包含尾部斜杠.这可能会破坏事物,例如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);
Run Code Online (Sandbox Code Playgroud)
在主程序中使用时,两者都是不同的.如果在DLL中使用,则第一个返回加载DLL的.EXE目录,第二个返回DLLs目录.