【问题标题】:IOException when trying to delete an image尝试删除图像时出现 IOException
【发布时间】:2020-07-09 08:20:30
【问题描述】:

我有一个个人资料页面,用户可以在其中更改他们的个人资料图片,当用户单击提交时,他们的旧个人资料图片将被删除并替换为新的。但是,当我尝试删除图像时,会出现以下错误:

IOException: 进程无法访问文件 'C:\Users\Shayan\source\repos\RestaurantWeb\RestaurantWeb\wwwroot\Images\Users\92487709-5b2f-417c-a64f-4661962693cf_imb5ohqzqr511.jpg' 因为它正被另一个进程使用。

这是我添加和删除图像的代码的 sn-p:

if (accountDetailsViewModel.ProfilePicture != null)
{
    string fileName = FileUploadHelper.GetUniqueFileName(accountDetailsViewModel.ProfilePicture.FileName);
    string filePath = FileUploadHelper.GetProfileFilePath(fileName, _webHostEnvironment);
    await accountDetailsViewModel.ProfilePicture.CopyToAsync(new FileStream(filePath, FileMode.Create));
    user.ProfileImagePath = fileName;

    string previousImageFilePath = FileUploadHelper.GetProfileFilePath(accountDetailsViewModel.PreviousPicturePath, _webHostEnvironment);
    if (System.IO.File.Exists(previousImageFilePath) && accountDetailsViewModel.PreviousPicturePath != "noprofilepic.jpeg")
    {
        System.IO.File.Delete(previousImageFilePath);
    }
}

为什么会这样?我是要关闭文件吗?我没有使用File.Create(),所以我不能像这样关闭它:

var img = File.Create(filePath);
img.Close();

【问题讨论】:

    标签: c# image asp.net-core


    【解决方案1】:

    尝试关闭您正在创建的FileStream

    编辑:查看this

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2016-01-20
      • 2013-07-09
      • 2010-09-21
      • 1970-01-01
      • 2011-07-25
      • 2020-01-05
      • 2015-07-26
      • 2014-09-06
      相关资源
      最近更新 更多