为什么可执行文件的当前路径返回空? (C#,Path.GetDirectoryName())

问题描述 投票:0回答:1

我创建了一个使用数据库文件进行工作的程序(C#)。

我使用一个字符串来表示该文件的路径(由 Path.GetDirectoryName() 函数返回),并在使用 Visual Studio 发布之前进行了工作。

所以我测试了publish方法生成的可执行文件,不幸的是,不起作用。我调查了这个问题,发现这个函数(Path.GetDirectoryName())为我的字符串路径返回了一个空值。为什么这个函数在发布方法之前起作用而在发布方法之后不起作用?

我尝试过的代码块:

    public class CargaDao 
    {
        static private string caminhoDoBanco = "";

        public void inicializarBanco()
        {
            string diretorioBase = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            caminhoDoBanco = Path.Combine(diretorioBase, "Gollog.db");
        }
    }
// there is more methods of course but is not relevant for the moment.

但是字符串,就像我说的,得到一个空值。

这个问题产生了其他问题,例如当我使用 Path.Combine() 时出现错误,因为我的字符串是为此函数传递的。

c# console-application .net-8.0
1个回答
0
投票

正如前面评论中所说,问题是因为 单文件部署 使得 Assembly.Location 在 .NET 5 及更高版本中返回空字符串。您可以尝试其他方法来获取可执行文件的当前绝对路径。

不幸的是,我没有看到使用 Assembly.Location 而不更改它们的依赖项的解决方案。如果是这种情况,您可以考虑更改部署方法。

© www.soinside.com 2019 - 2024. All rights reserved.