gpt4 book ai didi

c# - 尝试将图像保存到 wwwroot 时出现 DirectoryNotFoundException

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:37 26 4
gpt4 key购买 nike

使用 this question我想出了这段代码来保存文件

[HttpPost]
public IActionResult Upload(string office, IFormFile file)
{
if (file.Length > 0) {
var filePath = Path.GetFullPath(Path.Combine(_environment.WebRootPath,
_configuration["SydneyFloorplanPath"]));

using (var fileStream = new FileStream(filePath, FileMode.Create)) {
file.CopyTo(fileStream);
}
}
return RedirectToAction("Index", new{office = office});
}

但是在实例化 FileStream 时我遇到了一个非常烦人的问题:

An exception of type 'System.IO.DirectoryNotFoundException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Could not find a part of the path 'C:\images\Floorplan\sydney.pdf'.'

但这不是我需要的路径。 Images 文件夹位于我的项目中 wwwroot\images...

如果 WebRootPath 实际上没有给我一个可用的相对路径,那它还有什么意义呢?

注意 _environment 是一个注入(inject)的 IHostingEnvironment

我还注意到,如果我调用

var two = _environment.WebRootPath;

变量包含完整路径..."C:\\Users\\bassie\\source\\repos\\TFS\\DSSTools\\wwwroot"

但是在调用Path.Combine之后,我突然有了"C:\\images\\Floorplan\\sydney.pdf" ...为什么?

编辑:

_environment 是一个IHostingEnvironment,例如:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace AspNetCorePathMapping
{
public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;

public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}

public ActionResult Index()
{
string webRootPath = _hostingEnvironment.WebRootPath;
string contentRootPath = _hostingEnvironment.ContentRootPath;

return Content(webRootPath + "\n" + contentRootPath);
}
}
}

最佳答案

我设法让它工作

[HttpPost]
public IActionResult Upload(string office, IFormFile file)
{
var webRootPath = _environment.WebRootPath;
var floorPlanPath = _configuration["SydneyFloorplanPath"];

if (file.Length > 0) {
var filePath1 = Path.Combine(floorPlanPath,webRootPath.ReplaceFirst("/", ""));

using (var fileStream = new FileStream(filePath1, FileMode.Create)) {
file.CopyTo(fileStream);
}
}
return RedirectToAction("Index", new{office = office});
}

ReplaceFirst 是一个简单的 StringExtension

public static string ReplaceFirst(this string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return $"{text.Substring(0, pos)}{replace}{text.Substring(pos + search.Length)}";
}

看来 webRootPath 中的前导 / 破坏了我的 Path.Combine 调用

关于c# - 尝试将图像保存到 wwwroot 时出现 DirectoryNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50166842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com