我如何获得正确的应用程序目录?

How do i get right the directory of my application?

我制作了一个小型控制台应用程序(首次使用 C# 发布)。但我不能使用我的资源文件。我用textfiles可以给它。当我使用调试目录

时它起作用了

我的目标是创建一个这样的目录: 应用图 + application.exe + 设置 资源地图 + configurations.txt 记录器 +.

现在,如果我尝试访问配置文件,它会将我发送至: C:\Users\<username> \AppData\Local\Apps.0\D01L7N51.9EW\R7HB7NAB.B7Y \sele..tion_0000000000000000_0001.0000_92af5262ce6f49d8

虽然我在期待 C:/Users/<username>/ Documents/<application>/ + resources/config.txt

我试过了

string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Console.WriteLine(dir);

&&

Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));

&&

Console.WriteLine(Directory.GetCurrentDirectory());

但我总是在 appdata 地图上结束。

怎么样:

System.IO.Path.GetDirectoryName(Application.ExecutablePath);

您可以简单地使用 Application.StartupPath (reference),但结果将始终取决于您 place/install 可执行文件

的位置

如果你总是想指向当前用户的 Documents 文件夹(在操作系统中注册为一个特殊文件夹),就像你的例子一样,你可以使用:

String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

或(但风险自负,因为它不太安全):

String path = Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents");

使用第一种或第二种方法检索到正确的 Documents 文件夹路径后,将其与最后一部分结合起来:

path = Path.Combine(path, "resources/config.txt");

有关这两种方法的更多信息: