删除图像:进程无法访问该文件,因为它正由另一个进程使用

时间:2009-07-13 10:33:01

标签: asp.net

我正在使用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);

4 个答案:

答案 0 :(得分:2)

如何保存图像?您是否确保丢弃用于保存图像的所有图像和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))

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:1)

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

    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);
        }
    }

答案 3 :(得分:0)

尝试输入:

  

openfiles file_path_and_filename

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

并确保您拥有删除权限。

相关问题