【问题标题】:I am getting a path not found error when trying to access a path in my application folder [duplicate]尝试访问我的应用程序文件夹中的路径时出现找不到路径错误[重复]
【发布时间】:2021-03-24 04:03:20
【问题描述】:

Net Core 网络应用程序,具有用户可以上传照片的实用程序。它使用 API 控制器进行实际上传。我在解决方案中创建了一个名为 ImageStorage 的文件夹,其中文件夹路径如下所示:

G:\GameDevelopment\DungeonMaxer\MainApp\wwwroot\ImageStorage

我还在 ImageStorage 下创建了一个名为 uploads 的文件夹。

我正在尝试在本地(IIS Express)进行测试,并将这一行添加到控制器中:

[HttpPost("upload")]
public async Task<IActionResult> PostAsync(IFormFile file)
{

    // parent folder for storage
    var serverStoragePath = Server.MapPath(@"~/ImageStorage");

    // uploads folder inside the parent
    var fileRoute = Path.Combine(serverStoragePath, "uploads");

    // get file extension

    string extension = System.IO.Path.GetExtension(theFile.FileName);

    // create a new name for storage
    string name = Guid.NewGuid().ToString().Substring(0, 8) + extension;

    // get the link to the file
    string link = Path.Combine(fileRoute, name);

    using (FileStream writerFileStream = System.IO.File.Create(link))
    {
        await stream.CopyToAsync(writerFileStream);
        writerFileStream.Dispose();
    }

    // Return the file path as json
    Hashtable imageUrl = new Hashtable();
    imageUrl.Add("link", "/uploads/" + name);

    return Json(imageUrl);
}

但是当我在本地运行项目并在var serverStoragePath = Server.MapPath(@"~/ImageStorage");这一行上放一个断点时,我得到了这个错误:

 System.NullReferenceException: 'Object reference not set to an instance of an object.'

我也尝试了wwwroot\ImageStorage,但这给了我同样的错误。

有没有办法访问这个路径?

谢谢!

【问题讨论】:

  • 会不会只是权限问题?我假设您已经使用调试器检查了最终文件名是否正确。
  • @Steve 我知道路径存在于我的文件系统中。我还在 Microsoft 网站上查找了 Server.MapPath,我认为我使用它是正确的。
  • 调用 Server.MapPath 后 serverStoragePath 的值是多少?...这也可能不是应用程序基本路径设置为的位置
  • 等等。您是否尝试在 Asp.Net Core 项目中使用 Server.MapPath?没办法,需要通过DI使用IWebHostEnvironment,然后使用属性WebRootPath
  • Just Path.Combine WebRootPath 与您的文件夹/s

标签: c# asp.net-core asp.net-core-webapi


【解决方案1】:

IHostingEnvironment 用于 .Net Core 2.0 IWebHostEnvironment 已在 .Net Core 3.0 中取代 IHostingEnvironment。

public class HomeController : Controller
{
    private IHostingEnvironment Environment;
 
    public HomeController(IHostingEnvironment _environment)
    {
        Environment = _environment;
    }
 
    public IActionResult Index()
    {
        string wwwPath = this.Environment.WebRootPath;
        string contentPath = this.Environment.ContentRootPath;
 
        return View();
    }
}

【讨论】:

  • 哦,我明白了,但是我将如何调用我的路径,Server.MapPath(@"~/ImageStorage");?谢谢
  • String.Concat(wwwPath, "ImageStorage")
  • 谢谢,我在哪里定义 Enviroment.webRootPath?是在 Startup.cs 中吗?谢谢
  • 您可以在控制器构造函数中初始化 Environment,然后在 PostAsync 操作中使用 wwwPath。
猜你喜欢
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多