从 WPF 应用程序获取应用程序的目录

我找到了使用 AppDomain 的 Windows 窗体的解决方案,但 WPF Application对象的等价物是什么?

216165 次浏览
String exePath = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
string dir = Path.GetDirectoryName(exePath);

试试这个!

一种方法是:

System.AppDomain.CurrentDomain.BaseDirectory

另一种方法是:

System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)

还有一个:

System.Reflection.Assembly.GetExecutingAssembly().Location

还可以使用命令行参数的第一个参数:

String exePath = System.Environment.GetCommandLineArgs()[0]

您还可以自由使用 Application。来自 System 的 StartupPath。窗户。表单,但必须为 System 添加引用。窗户。集合!

试试这个,别忘了 using System.Reflection

string baseDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

我使用简单的 string baseDir = Environment.CurrentDirectory;和它的工作为我。

祝你好运

编辑:

我曾经删除这种类型的错误,但我更喜欢编辑它,因为我认为这个答案的负点帮助人们了解错误的方式。:)我明白上述解决方案是没有用的,我改为 string appBaseDir = System.AppDomain.CurrentDomain.BaseDirectory; 其他方法有:

1. string baseDir =
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
2. String exePath = System.Environment.GetCommandLineArgs()[0];
3. string appBaseDir =    System.IO.Path.GetDirectoryName
(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);

祝你好运

我试过了:

    label1.Content = Directory.GetCurrentDirectory();

还有目录。

我只是想给那些需要的人补充一个最新的答案。

我曾经使用: My.Application.Info.DirectoryPath来获取我的应用程序路径。看来 NET6不喜欢这样。在使用了下面的一个示例之后,我注意到 IntelliSense 建议使用以下代码: Environment.ProcessPath

因此,要获取应用程序 exe 的路径:

Environment.ProcessPath

获取文件夹:

Path.GetDirectoryName(Environment.ProcessPath)

希望这个能帮上忙。