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
相关产品推荐
相关产品推荐

