You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI Blazor .NET 8中Directory.GetCurrentDirectory()返回系统目录问题求助

解决MAUI Blazor中Directory.GetCurrentDirectory()路径不符问题

在MAUI Blazor应用里,Directory.GetCurrentDirectory()返回系统目录(比如Windows下的C:\Windows\system32)是因为应用运行时的当前工作目录并非项目输出目录。要定位到wwwroot文件夹,可采用以下可行方法:

方法一:通过应用基目录拼接wwwroot路径

用AppContext.BaseDirectory获取应用程序的基目录,再通过Path.Combine拼接出wwwroot的完整路径,这种方式适配多平台:

@page "/counter"

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
        // 获取应用基目录
        var baseDirectory = AppContext.BaseDirectory;
        // 拼接wwwroot路径
        var wwwrootPath = Path.Combine(baseDirectory, "wwwroot");
        // 示例:拼接具体图片路径
        var imageFilePath = Path.Combine(wwwrootPath, "images", "sample.jpg");

        if (File.Exists(imageFilePath))
        {
            // 将图片转换为Base64
            byte[] imageBytes = File.ReadAllBytes(imageFilePath);
            string base64Image = Convert.ToBase64String(imageBytes);
            // 后续处理Base64字符串
        }
    }
}

关键注意事项

  • 确保wwwroot下的目标文件(如图片)在项目属性中设置为复制到输出目录(右键文件→属性→复制到输出目录:选择“如果较新则复制”或“始终复制”),否则文件不会被打包到应用中。
  • 优先使用Path.Combine拼接路径,避免硬写路径分隔符(如/或\),保证跨平台兼容性。

内容的提问来源于stack exchange,提问作者Edgar Gomez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 16:54:57