【问题标题】:Delete Image: The process cannot access the file because it is being used by another process删除映像:该进程无法访问该文件,因为它正被另一个进程使用
【发布时间】:2021-07-23 14:13:05
【问题描述】:

我正在使用 asp.net C#。我将图像文件保存在文件夹中并将其删除。当我删除它时出现错误“该进程无法访问文件 'C:\Inetpub\wwwroot\Admin\Temp\visible_Jul-13-2009_035606.png' 因为它正在被另一个进程使用”

代码:

fupAddImage.PostedFile.SaveAs(Server.MapPath("Temp") + @"\" + tempFilename);
File.Delete(Server.MapPath("Temp") + @"\" + tempFilename);

【问题讨论】:

  • 添加特定信息...您如何保存图像以及如何使用它来删除它。如果您可以在此处发布您的代码部分。
  • fupAddImage.PostedFile.SaveAs(Server.MapPath("Temp") + @"\" + tempFilename); File.Delete(Server.MapPath("Temp") + @"\" + tempFilename);
  • 可能是asp.net进程无权删除文件。

标签: asp.net


【解决方案1】:

如何保存图像?您是否确保已处理所有用于保存图像的 Image 和 Stream 对象?由于ImageStream(和StreamWriter)都实现了IDisposable,因此您应该确保调用Dispose(或在创建对象时使用块设置),以便在图像具有已保存。

更新:您可以尝试的一件事是自己保存图像数据,以便更好地控制它是如何完成的:

private static void SaveFile(Stream input, string fileName)
{
    using (Stream output = File.OpenWrite(fileName))
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        do
        {
            bytesRead = input.Read(buffer, 0, buffer.Length);
            output.Write(buffer, 0, bytesRead);
        } while (bytesRead == buffer.Length);
    }
}

// Pass the uploaded file data to the above method like this:
SaveFile(fupAddImage.FileContent, Path.Combine(Server.MapPath("Temp"), tempFilename))

【讨论】:

  • 投反对票的原因是什么?如果我的示例中有任何错误,很高兴知道它可以修复...
【解决方案2】:

您需要发布一些代码才能确定,但​​文件可能仍在某处打开,因此您的应用程序尚未释放文件锁定。在删除之前尝试关闭所有打开的流并处理指向该对象的所有文件句柄。

您可能还需要等待操作系统在处理完所有指向它的句柄后释放文件。

我猜问题出在上面。如果您正在创建一个文件并在下一行删除它,那么操作系统可能甚至还没有将文件刷新到磁盘,更不用说释放文件句柄和锁了。尝试在写入和删除之间留出一些时间,看看是否可以再次删除。

【讨论】:

    【解决方案3】:

    您可以使用此代码上传和删除图像或文件

        public class UploadFileTools
    {
        private string _path = string.Empty;
        private string _fileType = string.Empty;
        private string _filename = string.Empty;
        private IFormFile _file = null;
    
        public string path
        {
            get { return this._path; }
            set { this._path = value; }
        }
        public string FileType
        {
            get { return this._fileType; }
            set { this._fileType = value; }
        }
        public IFormFile file
        {
            get { return file; }
            set { this._file = value; }
        }
        public string Filename
        {
            get { return _filename; }
            set { _filename = value; }
        }
    
        public bool Upload()
        {
            try
            {
                string filePath = string.Format("{0}{1}{2}", _path, _filename, _fileType);
           if (_file.Length > 0)
                {
                    if (!Directory.Exists(_path))
                        Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        _file.CopyTo(fileStream);
                        return true;
                    }
                }
                 else
                    throw new Exception("Error!!! The file has a problem");
    
            }
            catch (Exception ex)
            {
                throw new Exception("Error !!! Your file could not be uploaded"+ex.Message);
            }
        }
    
        public void RemoveFile(string path = null)
        {
            try
            {
    
            string serverPath = path;
            if (string.IsNullOrEmpty(serverPath))
                serverPath = string.Format("{0}{1}{2}", _path, _filename, _fileType);
            if (File.Exists(serverPath))
            {
                File.Delete(serverPath);
            }
            }
            catch (Exception ex)
            {
    
                throw new Exception(ex.Message);
            }
    
        }
    }
    

    查看模型:

        public class SendFormViewModel
    {
        public IFormFile myFile { get; set; }
    }
    

    在控制器中调用

            private readonly IHostingEnvironment _hostingEnvironment;
    
        public HomeController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
    
        [HttpPost]
        public IActionResult save(SendFormViewModel model)
        {
            string fileName = string.Empty;
            string extension = string.Empty;
    
            try
            {
    
                if (model.myFile != null && model.myFile.Length > 0)
                {
                    var allowedExtensions = new[] { ".png", ".jpg", ".jpeg" };
                    extension = Path.GetExtension(model.myFile.FileName);
                    if (allowedExtensions.Contains(extension.ToLower()) &&
                        model.myFile != null&& model.myFile.Length > 0)
                    {
                        UploadFileTools _up = new UploadFileTools();
                        string webRootPath = _hostingEnvironment.WebRootPath;
                        string staticPath = "/img/";
                        string path = webRootPath + staticPath;
                        fileName = "myImg";
                        _up.FileType = extension;
                        _up.Filename = fileName;
                        _up.path = path;
                        _up.file = model.myFile;
                        _up.RemoveFile(webRootPath + "/img/myImg" + extension);
                        if (_up.Upload())
                        {
                            return Json("ok");
                        }
                    }
                }
                return Json("ok");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
    

    【讨论】:

      【解决方案4】:

      尝试输入:

      打开文件文件路径和文件名

      在命令提示符(cmd.exe)中查找原因。

      并确保您拥有删除权限。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-10
        相关资源
        最近更新 更多